我正在尝试选择具有特定列名称的行,并按其他列名称排序。
这是我的问题,进入N个简化表:
table 1: id, username, datetime, comment
table 2: id, username, datetime, vote
table N: id, username, datetime, bought
我希望能够在所有N个表中选择按日期时间排序的username='Some Name'
的所有行。
-
顺便说一下,有没有人知道学习和练习高级SQL的好书或资源? (尝试过SQLZoo,但是他们没有足够的先进例子......然后还有太高级的例子,我仍然难以接受)
答案 0 :(得分:7)
如果您希望同时对所有表格进行排序(表3中的较新记录显示在表2中的某些表格之前),
跨多个表执行此操作的最简单方法是使用UNION:
(SELECT id, username, datetime FROM table 1 WHERE username = 'Some Name')
UNION
(SELECT id, username, datetime FROM table 2 WHERE username = 'Some Name')
UNION
(SELECT id, somethingelse AS username, date as datetime FROM table 3 WHERE somethingelse = 'Some Name')
....
ORDER BY datetime DESC
请注意,当您使用这样的联合时,所有的select语句都应该返回相同数量的列并且命名相同(您可以使用别名,如我在上面的表3中所示)
答案 1 :(得分:2)
在查询中对表进行别名,即
SELECT t1.id, t2.username, ... FROM table1 as t1
答案 2 :(得分:1)
您可以从不同的表中选择相同的列名称,如:
SELECT table1.username as t1user, table2.username as t2user...
答案 3 :(得分:1)
您可以使用UNIONS
选择必须是这样的:
(SELECT comment, date FROM table1 WHERE username='Some Name')
UNION
(SELECT vote, date FROM table2 WHERE username='Some Name')
...
UNION
(SELECT bought, date FROM tableN WHERE username='Some Name')
ORDER BY date LIMIT 100;
答案 4 :(得分:-1)
display_error($this->entity);
$result = get_leave_status($this->entity);
start_table(TABLESTYLE, "width=60%");
$th = array(_("#"),
_("Login Date"),
_("Login Time"),
_("Reason"),
_("Status"),
_(" "),
);
table_header($th);
$sl=1;
while($sl<13){
display_error($sl);
$str = ($sl < 10) ? 0 . $sl : $sl;
$sql="SELECT login_time,login_date,early_leave_reason FROM ".TB_PREF."hcm_attendance_".$str." WHERE emp_code=". db_escape($this->entity);
$sl++;
$result = db_query($sql, "Can't make query in loan_req table.");
$k = 0;
$i = 1;
while ($myrow = db_fetch($result)) {
alt_table_row_color($k);
label_cell($i,'align=center');
label_cell(sql2date($myrow["login_date"]),'align=center');
label_cell($myrow["login_time"],'align=center');
label_cell($myrow["early_leave_reason"], "Width=30%");
if ($myrow["status"] == 1)
label_cell('Approved');
elseif ($myrow["status"] == 2)
label_cell('Rejected');
else {
label_cell(viewer_link('Pending',"payroll/inquiry/leave_document.php?eno=".$this->vendor_no.'&lid='.$myrow['id']));
edit_button_cell("{$this->name}Edit[{$myrow['id']}]", _("EDIT"));
}
end_row();
$i++;
}
}
end_table(1);
here i have used $sl to increment table name like 0_hcm_attendance_01,0_hcm_attendance_02 -------to 0_hcm_attendance_12
here TB_PREF=0;
TB_PREF."hcm_attendance_".$str