MYSQL或一列上的两个值

时间:2014-09-20 04:40:32

标签: php mysql sql

我有2张桌子。

表1:tA

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

表2:tB

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

预期输出

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

mysql代码:

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

来自我的mysql代码:

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

我该怎么办?

3 个答案:

答案 0 :(得分:0)

通过tA_id删除您的组,因为它将cat_name Mobile和其他组合在一起。

如果您需要保持使用ORDER BY tB.cat_id ASC我相信会像您需要的那样显示cat_id 1和2

答案 1 :(得分:0)

查询中存在错误... JOIN缺失...

<强> 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

这是获取预期结果

+----+---------------------+-----+--------+--------+----------+
| 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  |
+----+---------------------+-----+--------+--------+----------+

答案 2 :(得分:0)

试试这个: -

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;

希望它会对你有所帮助。