如何检查数据库中的多行

时间:2014-03-14 15:12:35

标签: php mysql

假设我有2列,大小和颜色,表的内容如下:

sizes  colors

large  red
large  green
small  green

如果我想要检索large表中sizesgreen表中colors的记录,我会这样做:

$q = "SELECT * FROM tablename WHERE sizes='large' and colors='green'";

但是,如果我只想在行中同时包含largered来修改green该怎么办?

1 个答案:

答案 0 :(得分:3)

您似乎需要检查匹配的2行。自联接可能是最简单的方法: -

SELECT *
FROM SomeTable a
INNER JOIN SomeTable b
ON a.sizes = b.sizes
WHERE a.sizes = 'large'
AND a.colors = 'red'
AND b.colors = 'green'

避免使用JOIN,但这只返回大小(你还有其他想要返回的列吗?): -

SELECT sizes, COUNT(DISTINCT colors) AS colour_count
FROM SomeTable
WHERE sizes = 'large'
AND colors IN ('red', 'green')
GROUP BY sizes
HAVING colour_count = 2