计算记录和打印行

时间:2016-06-08 14:39:31

标签: mysql sql

我希望mysql选择包含SECRETKEY = 'ts17'的记录,然后使用tb_dailyshowSECRETKEY = 'ts17'计算DATE = '20160608'中的记录(如果tb_dailyshow中的所有记录都是10来自NAME表的tb_namestb_names行。{/ p>

第一张表ID | SECRETKEY | NAME --------------------- 1 | ts17 | Chris

tb_dailyshow

第二张表ID | SECRETKEY | DATE -------------------- 1 | ts17 | 20160608 2 | ts17 | 20160608 3 | fa99 | 20160608

SELECT n.* 
FROM tb_adv n 
INNER JOIN tb_shown ds 
ON ds.uid = n.uid 
  AND ds.date = '20160607' 
WHERE n.uid = '575474d715154' 
GROUP BY n.id 
HAVING COUNT(*)<10

我的mysql行:

$q = "SELECT n.* 
FROM tb_adv n 
INNER JOIN tb_shown ds 
ON ds.uid = n.uid 
  AND ds.date = '20160607' 
WHERE n.uid = '575474d715154' 
GROUP BY n.id 
HAVING COUNT(*)<10";
$select = mysqli_query($con, $q);
while($row = mysqli_fetch_array($select)){
  echo $row['text'];
}

php code:

    /* CSS used here will be applied after bootstrap.css */

.table .checkbox-container {
  vertical-align: top;
  padding: 0;
}

.table .checkbox-container .input-group {
  height: 100%;
}

.table .checkbox-container .input-group-addon {
  border: none;
  border-radius: 0;
  background-color: red;
}

.table .checkbox-container .input-group > input {
  padding: 0;
  border: none;
  border-radius: 0;
  outline: none;
  height: 100%;
}

.table .box {
  height: 100%;
  padding: 0;
  display: inline-block;
}

.table-bordered>tbody>tr>td, .table-bordered>tbody>tr>th, .table-bordered>tfoot>tr>td, .table-bordered>tfoot>tr>th, .table-bordered>thead>tr>td, .table-bordered>thead>tr>th{
  vertical-align: middle;
}

2 个答案:

答案 0 :(得分:1)

select tb_names.name, count(*)
from tb_names 
join tb_dailyshow 
 on tb_names.secretkey = tb_dailyshow.secretkey 
where tb_dailyshow.date = '20160608'
group by tb_names.name
having count(*) < 10

答案 1 :(得分:0)

http://sqlfiddle.com/#!9/148e1e/1

SELECT n.*
FROM tb_names n
INNER JOIN tb_dailyshow ds
ON ds.secretkey = n.secretkey
  AND ds.date = '20160608'
WHERE n.secretkey = 'ts17'
GROUP BY n.id
HAVING COUNT(*)<10

要调试代码,请转换此部分:

$select = mysqli_query($con, $q);
while($row = mysqli_fetch_array($select)){
  echo $row['text'];
}

到此:

if($select = mysqli_query($con, $q)) {
  while($row = mysqli_fetch_array($select)){
    echo $row['text'];
  }
} else {
  echo "Query failed with error: ".mysqli_error($conn);
}

更新如果您需要获取记录即使没有dailyshows,您也可以将INNER JOIN更改为LEFT JOIN

http://sqlfiddle.com/#!9/6472a/3

SELECT n.*
FROM tb_names n
LEFT JOIN tb_dailyshow ds
ON ds.secretkey = n.secretkey
  AND ds.date = '20160608'
WHERE n.secretkey = 'ts18'
GROUP BY n.id
HAVING COUNT(*)<10