2011-03-22 50 views
0

當使用Select語句顯示來自Mysql Db的數據時。我得到重複值。如何解決這個問題?我的SQL查詢是這樣的:連接表時獲取重複結果

$sql="SELECT r.hosteladmissionno,r.student_name,r.semester, 
     m.billmonth,m.billyear,m.wastagecharge,b.exp_amount 
    FROM registration r, messexp m, blockexp b 
    WHERE r.mess_type = '".$q."' AND r.mess_type=m.messtype AND r.status_flag=1"; 
+0

請格式化SQL,以便我們不必滾動 – 2011-03-22 06:46:35

+0

我已編輯它.. – Coolbreeze 2011-03-22 06:51:45

+0

在'select'後面使用'DISTINCT'選擇' – diEcho 2011-03-22 06:53:32

回答

3

你應該在你的查詢中使用內連接。否則登記的每個結果將與messexp的每個結果進行組合...

$sql="SELECT registration.hosteladmissionno, 
    registration.student_name, 
    registration.semester, 
    messexp.billmonth, 
    messexp.billyear, 
    messexp.wastagecharge, 
    blockexp.exp_amount 
FROM registration 
INNER JOIN messexp ON (messexp.id_registration = registration.id) 
INNER JOIN blockexp ON (blockexp.id_messexp = messexp.id) 
WHERE 
registration.mess_type = '".$q."' AND status_flag=1"; 

請注意,(...)將改變這取決於你的架構

+0

謝謝,我會嘗試..freye .. id_registration從哪裏來? – Coolbreeze 2011-03-22 07:12:26

+1

@Dinzy這是你的模式的假設。通常,要在兩個表之間建立關聯,您使用的是來自兩個表中的一個的id。例如。 Tables => Student(id,lastname,firstname,id_class ...)和Class(id,name,description等)。你有一個學生和一個班級之間的聯繫。這意味着學生是在id_class – 2011-03-22 07:27:43

+0

由id_class引用類謝謝freyre .. – Coolbreeze 2011-03-22 09:07:44

3

你跨連接的表,所以你得到每一個結果的組合。 連接表的where子句中:

select tab1.column1, table2.column1 
from tab1, tab2 
where tab1.fkColumn = tab2.idColumn 

什麼是連接表彼此列?

+0

我已編輯我的問題上面..檢查它 – Coolbreeze 2011-03-22 07:08:06

+0

你也必須連接表格blockexp。否則,你會像以前一樣交叉加入。 – 2011-03-22 07:15:36