基本上,我有一个将数据导出为excel的csv格式的函数...我正在尝试使用单个查询来选择所选时间段内的所有销售记录,但我需要第一列被查询来自另一张桌子。我当前的查询如下:
$select = "SELECT `record_date` AS 'Sale Date',
`record_order_number` AS 'Order #',
`record_activity_number` AS 'Activity #',
`record_total_diy_revenue` AS 'Revenue $'
FROM st_entered_records
WHERE `record_user_id` = '$this->user_id' AND
`record_date` BETWEEN '$this->start_date' AND '$this->end_date' ";
之前
`record_date` AS 'Sale Date'
我需要它来运行第二个选择以获取用户名和格式的名字:
"LastName, FirstName"
(user_last_name)", "(user_first_name) from a second table (st_users)
where `user_id` = '$this->user_id'
任何帮助将不胜感激! :)
答案 0 :(得分:1)
你可以做一个连接示例:
SELECT t2.lastName,t2.firstName,
t1.record_date AS 'Sale Date',
t1.record_order_number AS 'Order #',
t1.record_activity_numbe AS 'Activity #',
t1.record_total_diy_revenue AS 'Revenue $'
FROM st_entered_records1 t1
INNER JOIN stusers t2 ON t1.record_user_id=t2.userid
WHERE t1.userid = $this->user_id AND
t1.record_date BETWEEN $this->start_date AND $this->end_date
请确保您匹配表名和字段名,我相信您已经知道这一点:)
编辑:Stongly advise you do not use MYSQL_*
原因:
This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQL extension should be used.
答案 1 :(得分:0)
尝试
SELECT
`st_entered_records`.`record_date` AS 'Sale Date',
`st_entered_records`.`record_order_number` AS 'Order #',
`st_entered_records`.`record_activity_number` AS 'Activity #',
`st_entered_records`.`record_total_diy_revenue` AS 'Revenue $',
`st_users`.`user_last_name` AS 'LastName',
`st_users`.`user_first_name` AS 'FirstName',
FROM `st_entered_records`
INNER JOIN `st_users` ON `st_entered_records`.`record_user_id` = `st_users`.`user_id`
WHERE
`record_user_id` = :uid AND
`record_date` BETWEEN :startDate AND :endDate;
顺便说一下,我用命名参数替换了变量。我强烈建议使用预准备语句,但如果你坚持使用连接查询(无论是使用mysql,mysqli还是PDO),请记住转义变量!