这是我的php代码:
$trsql = "SELECT * from members order by id desc";
$trresult = mysql_query($trsql);
$count = mysql_num_rows($trresult);
while ($trrow = mysql_fetch_array($trresult)) {
$bill_membertotal = mysql_query("SELECT * FROM billing WHERE suite='$trrow[suite]' order by bill_id desc limit 1");
$bill_membercount = mysql_fetch_array($bill_membertotal);
$check_membertotal = mysql_query("SELECT SUM(net) AS checker FROM billing WHERE suite='$trrow[suite]'");
$check_membercount = mysql_fetch_assoc($check_membertotal);
echo $trrow['col1'] $trrow['col2'] $trrow['col1'] $bill_membercount['balance'] $check_membercount['checker'] ;
}
会员表: [id suite col1 col2 col 3] 结算表 [bill_id套房毛费净余额]
问题:如何使用1个查询进行此3查询?我知道MYSQL Join函数。但是在这种情况下怎么做?
答案 0 :(得分:1)
select * ,
(select count(*) from members) as members_count,
(select count(*) from billing where suite = bill.suite) as bill_count,
(select count(*) from billing where suite = check.suite) as check_count,
from members members
inner join billing bill on members.suite = bill.suite
inner join billing check members.suite = check.suite
答案 1 :(得分:1)
未经测试:
$query = "SELECT
`member`.`col1` AS `col1`,
`member`.`col2` AS `col2`,
`bill`.`balance` AS `balance`,
SUM(`bill`.`net`) AS `checker`
FROM
`members` AS `member`,
`billing` AS `bill`,
WHERE
`bill`.`suite`=`member`.`suite`
ORDER BY
`member`.`id`,
`bill`.`bill_id`
DESC";
$results = mysql_query($query);
$count = mysql_num_rows($results);
while($entry = mysql_fetch_array($results)) {
printf('%s, %s, %s, %s, %s', $entry['col1'], $entry['col2'], $entry['col1'], $entry['balance'], $entry['checker']);
}
mysql _ * 标记为已弃用
答案 2 :(得分:1)
不确定,但请试一试,因为这是您的报告所期望的
http://sqlfiddle.com/#!2/7ccc6/3
查询:
SELECT m.*, COUNT(b.id) as member_count, SUM(net) as checker
FROM member m
JOIN billing b ON m.suite = b.suite
GROUP BY b.suite
答案 3 :(得分:1)
这似乎给出了预期的结果;因为你只需要一个字段的最后一个账单而MySQL没有分析函数,所以子查询比连接更容易解决该字段。
SELECT id member_id, col1, col2, col3,
(SELECT balance
FROM billing b1
WHERE b1.suite=m.suite
ORDER BY bill_id DESC LIMIT 1) balance,
SUM(net) AS checker
FROM members m
LEFT JOIN billing b
ON m.suite = b.suite
GROUP BY col1,col2,col3,id
ORDER BY id DESC