SQL Query选择多行

时间:2013-12-06 08:57:13

标签: mysql sql jointable

我有以下表格:

projects: id, name, language
          1 |test | php
          2 |test | java
          3 |hello| php


attrs:  id, name,      value,   tb1_id
        1  | status    | finish | 1
        2  | reference | 2      | 1

我需要一个查询来选择所有项目,这些项目具有另一个项目的“引用”属性并且“状态”完成。

示例输出:

id, name      
1 |test 

你能帮帮我吗?

4 个答案:

答案 0 :(得分:1)

SELECT P.id, P.name
FROM projects P inner join attrs A on P.id = a.tb1_id
WHERE (A.name = 'status' AND value = 'finish')
UNION
SELECT P.id, P.name
FROM attrs A INNER JOIN projects P ON A.value = P.id
WHERE A.name='reference'

查看this fiddle

中的结果

答案 1 :(得分:1)

你可以:

  • 对连接的表进行分组,在HAVING子句中使用合适的聚合函数过滤这些组:

    SELECT   projects.id, projects.name
    FROM     projects
        JOIN attrs ON attrs.tb1_id = projects.id
    GROUP BY projects.id
    HAVING   SUM(attrs.name='reference')
         AND SUM(attrs.name='status' AND attrs.value='finish')
    
  • 或多次加入attrs

    SELECT   p.id, p.name
    FROM     projects AS p
        JOIN attrs    AS r ON  r.tb1_id = p.id
                           AND r.name   = 'reference'
        JOIN attrs    AS s ON  s.tb1_id = p.id
                           AND s.name   = 'status'
    WHERE    s.value = 'finish'
    

答案 2 :(得分:0)

试试这个:

SELECT p.id, p.name
FROM projects p 
INNER JOIN (SELECT tb1_id, MAX(IF(a.name = 'status', a.value, '')) attrStatus, MAX(IF(a.name = 'reference', a.value, '')) attrReference
                FROM attrs a GROUP BY tb1_id) A ON p.id = A.tb1_id AND A.attrStatus = 'finish' 
WHERE EXISTS (SELECT 1 FROM projects p1 WHERE A.attrReference = p1.id)

检查SQL FIDDLE DEMO

<强>输出

| ID | NAME |
|----|------|
|  1 | test |

答案 3 :(得分:0)

您需要加入attrs两次,每个属性一次;

SELECT p.*, ref_attr.value reference FROM projects p
JOIN attrs ref_attr  ON ref_attr.tb1_id = p.id
                    AND ref_attr.name = 'reference'
JOIN attrs stat_attr ON stat_attr.tb1_id = p.id
                    AND stat_attr.name = 'status'
                    AND stat_attr.value = 'finish'

An SQLfiddle to test with