2013-06-04 35 views
2

我有2個表,見下面 - 型材是我的主要/主表MySQL的搜索2代表與重疊

profiles   invoices 
____________  ___________________ 
|id Name |  |profileid paid | 
|============|  |===================| 
|1 Abraham |  | 2   unpaid | 
|2 Martin |  | 3   unpaid | 
|3 John  |  | 3   paid | 
|____________|  |___________________| 

如可以看到的,亞伯拉罕具有0發票,馬丁1張未付帳單,和John有2張發票; 1付,1未付。

我要搜索:

  1. 所有支付的發票型材(約翰)
  2. 所有未付發票型材(約翰&馬丁)
  3. 所有有償和無償發票型材(S )(約翰)

我可以做圖1和2細,但具有與第3步

一個問題IM 210

這裏是我的查詢1;

$query = "SELECT DISTINCT profiles.name 
FROM profiles LEFT JOIN invoices ON (profiles.id=invoices.profileid) 
AND (invoices.paid='paid' OR invoices.paid='unpaid') 
WHERE 
IFNULL(invoices.paid, '') LIKE 'paid'; 

這裏是我的查詢2;

$query = "SELECT DISTINCT profiles.name 
FROM profiles LEFT JOIN invoices ON (profiles.id=invoices.profileid) 
AND (invoices.paid='paid' OR invoices.paid='unpaid') 
WHERE 
IFNULL(invoices.paid, '') LIKE 'unpaid'; 

這裏是我的查詢3;

$query = "SELECT DISTINCT profiles.name 
FROM profiles LEFT JOIN invoices ON (profiles.id=invoices.profileid) 
AND (invoices.paid='paid' OR invoices.paid='unpaid') 
WHERE 
IFNULL(invoices.paid, '') LIKE 'paid' 
AND IFNULL(invoices.paid, '') LIKE 'unpaid' 
; 

如上所述,1 & 2工作正常,但3給我0結果。 任何幫助,非常感謝。謝謝

+0

由於您希望從發票表中獲取多個維度,因此您希望在最後一條語句中使用右連接嗎? – Scuzzy

+1

不,RIGHT加入會(並且只會)給我所有具有發票的配置文件,它不會考慮那些沒有任何發票的配置文件。即,如果我只是選擇所有配置文件;它只會給我馬丁&約翰 – Lan

回答

2

您需要選擇invoices表2次,以獲得某人有付費和無付費的位置。試着這麼做 -

SELECT DISTINCT profiles.name 
FROM profiles 
LEFT JOIN invoices i1 ON (profiles.id=i1.profileid) 
AND (i1.paid='paid') 
LEFT JOIN invoices i2 ON (profiles.id=i2.profileid) 
AND (i2.paid='unpaid') 
WHERE 
IFNULL(i1.paid, '') LIKE 'paid' 
AND IFNULL(i2.paid, '') LIKE 'unpaid'; 

看到這個sqlfiddle例子 - http://sqlfiddle.com/#!2/ee4e2/4

+0

是的,非常好!而已。非常感謝 – Lan

0

一種可能性是一個子查詢數與輪廓

SELECT `profiles`.`name` 
FROM `profiles` 
WHERE (
    SELECT count(DISTINCT `subinvoices`.`paid`) 
    FROM `invoices` AS `subinvoices` 
    WHERE `profiles`.`id` = `subinvoices`.`profileid` 
    AND (`subinvoices`.`paid` = 'paid' OR `subinvoices`.`paid` = 'unpaid') 
) = 2 
0

要做到這一點,最簡單的方式相關聯的不同發票類型與聚合:

select p.*, coalesce(InvoiceInfo, 'NONE') 
from profiles p left outer join 
    (select profileid, 
      (case when sum(paid = 'PAID') > 0 and sum(paid = 'UNPAID') > 0 then 'BOTH' 
        when sum(paid = 'PAID') > 0 then 'PAID-ONLY' 
        when sum(paid = 'UNPAID') > 0 then 'UNPAID-ONLY' 
       end) as InvoiceInfo 
     from invoices i 
    ) 
    on p.id = i.profileid 

這可以讓你得到所有th同時提供三種類型的信息。例如,您可以通過以下方式計算每個組中的人員:

select coalesce(InvoiceInfo, 'NONE'), count(*) 
from profiles p left outer join 
    (select profileid, 
      (case when sum(paid = 'PAID') > 0 and sum(paid = 'UNPAID') > 0 then 'BOTH' 
        when sum(paid = 'PAID') > 0 then 'PAID-ONLY' 
        when sum(paid = 'UNPAID') > 0 then 'UNPAID-ONLY' 
       end) as InvoiceInfo 
     from invoices i 
    ) 
    on p.id = i.profileid 
group by coalesce(InvoiceInfo, 'NONE')