选择具有相同列值的行

时间:2013-11-26 10:32:42

标签: mysql

鉴于下面的表结构,我如何只选择给定名称和user_id具有相同根和级别值的行?

    Category
    +----+---------+------+------+-------+
    | id | user_id | name | root | level |
    +----+---------+------+------+-------+
    |  1 |      10 | wzq  |    1 |     1 |
    |  2 |      11 | xyz  |    2 |     1 |
    |  3 |      10 | xyz  |    2 |     2 |
    |  4 |      10 | xyz  |    2 |     2 |
    +----+---------+------+------+-------+   

我现在还选择了不具有相同根和级别的行

SELECT `c`.`id`, `c`.`user_id`, `c`.`name`, `c`.`root`, `c`.`level`
FROM `category` `c`
WHERE c.id IN (SELECT d.id FROM category AS d WHERE c.root=d.root AND c.level=d.level ) AND c.user_id = 10 AND c.name = 'xyz'
ORDER BY `c`.`id`

对于上面的示例,只应返回第3行和第4行

3 个答案:

答案 0 :(得分:1)

尝试使用仅选择具有相同根和级别的行 {/ 1}}

root=level

答案 1 :(得分:1)

SELECT x.* 
  FROM my_table x 
  JOIN my_table y 
    ON y.user_id = x.user_id
   AND y.root = x.root 
   AND y.level = x.level 
   AND y.id <> x.id
 WHERE x.user_id = 10 

答案 2 :(得分:0)

试试这个:

SELECT *
FROM
(
    SELECT root, level
    FROM category 
    WHERE name = 'xyz' AND user_id = 10
) x JOIN category c ON x.root = c.root