How to Show a Where Clause Just for One Field in MySQL

Use WHERE clause only for one column

If you want both strays and pets separately, then you can use aggregation:

SELECT (CASE WHEN d.owner IS NULL THEN 'stray' ELSE 'pet' END) as status,
COUNT(*) as dogs_count, SUM(d.age) AS total_age
FROM dogs d
GROUP BY status;

You can also use conditional aggregation to put the values all in one row:

SELECT COUNT(*) as dogs_count, SUM(d.age) AS total_age,
SUM(d.owner IS NULL) as num_strays,
SUM(CASE WHEN d.owner IS NULL THEN d.age ELSE 0 END) as strays_age
FROM dogs d

WHERE Clause for 1 field

Try below query ...

SELECT
A.GROUP_ID,
A.GROUP_DESC,
CASE WHEN B.GROUP_ID IS NULL THEN '0' ELSE '1' end as status
FROM dbo.GROUP_MASTER A
LEFT JOIN (SELECT * FROM dbo.GROUP_ASSIGN WHERE LOG_NAME LIKE 'ACCOUNT') B ON (A.GROUP_ID = B.GROUP_ID)

SQL condition on only 1 column

You can use a conditional SUM() in the first query, as in:

SELECT
max(i.created) AS creation,
l.label AS activite,
COUNT(*) AS nbTicket,
SUM(case when i.created LIKE "2019-01-%" then 1 end) AS nbEntree
FROM label AS l INNER JOIN
jiraissue AS i
ON (l.issue = i.id) AND i.issuetype <> 3
GROUP BY activite

WHERE clause on one field

Should simply be:

select count(id) id_count, count(lang) NOT_NULL_LANG FROM TABLE_NAME;
  • The COUNT() function, like most all SQL aggregation functions, excludes NULL from calculations

SELECT one column where condition is met

The way you've got your data structured you can just do

SELECT [row info you need]
FROM `table`
WHERE Name_1 LIKE '%value%'
OR Name_2 LIKE '%value%'
OR Name_3 LIKE '%value%'

Or by using a full-text index (you would need to create the index first):

SELECT [row info you need]
FROM `table`
WHERE MATCH( names ) AGAINST ( 'value' )

Obviously using either of these won't tell you which column has matched.

But you might be better off redesigning your schema like this

table
-----
id
[other info]

names
-----
id
name

tables_names
------------
table_id
name_id

That way you could do a simple INNER JOIN and avoid having the separate OR clauses and you will be able to tell which value has matched your query very easily.

WHERE clause for each SELECT field?

You can use a case statement

SELECT SUM(case when `for`=5 then `amount` else 0 end) - 
SUM(case when `by`=5 then `amount` else 0 end)
FROM table

that adds amount only for a specific case and 0 otherwise.



Related Topics



Leave a reply



Submit