简体   繁体   中英

MYSQL OR two values on one column

I have 2 tables.

Table 1: tA

+----+--------------------+
| id | url                |
+----+--------------------+
| 1  | hxxp://www.aaa.com |
| 2  | hxxp://www.bbb.com |
+----+--------------------+

Table 2: tB

+----+-------+--------+----------+
|id  | tA_id | cat_id | cat_name |
+----+-------+--------+----------+
| 1  |   1   |    1   |  Mobile  |
| 2  |   1   |    2   |  Other   |
| 3  |   2   |    2   |  Other   |
+----+-------+--------+----------+

Expected Output

+----+-------+--------+----------+
| id | tA_id | cat_id | cat_name |
+----+-------+--------+----------+
| 1  |   1   |    1   |   Mobile |
| 3  |   2   |    2   |   Other  |
+----+-------+--------+----------+

mysql code:

select * 
from tA 
inner tB 
on tA.id = tB.tA_id 
where tB.cat_id = 1 
or tB.cat_id = 2 
Group By tA_id

result from my mysql code:

+----+-------+--------+----------+
| id | tA_id | cat_id | cat_name |
+----+-------+--------+----------+
| 1  |   1   |   2    |   Other  |
| 3  |   2   |   2    |   Other  |
+----+-------+--------+----------+

How do I do?

Remove your group by tA_id because it is grouping cat_name Mobile and Other together.

If you need to keep it use ORDER BY tB.cat_id ASC which i believe will show the cat_id 1 and 2 like you need it

There is an error in query... JOIN is missing...

QUERY

SELECT * 
FROM tA 
INNER JOIN tB 
ON tA.id = tB.tA_id 
WHERE tB.cat_id = 1 
OR tB.cat_id = 2 
GROUP BY tA_id

This is fetching expected results

+----+---------------------+-----+--------+--------+----------+
| id |  url                |  id |  tA_id | cat_id | cat_name |
+----+---------------------+-----+--------+--------+----------+
| 1  | hxxp://www.aaa.com  |  1  |   1    |  1     |   mobile |
| 2  | hxxp://www.bbb.com  |  3  |   2    |  2     |   other  |
+----+---------------------+-----+--------+--------+----------+

Try this :-

select * 
from tA 
inner join tB 
on tA.id = tB.tA_id 
where tB.cat_id = 1 
or tB.cat_id = 2 
group by tb.cat_name;

Hope it will help you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM