dstobkpm908182 2018-01-23 18:17
浏览 68

从PHP中准备好的MySQL语句的结果中计算唯一值

I have an online calendar listing upcoming live music. I use a prepared statement to fetch the listings for the next eight days and display them in a table. What I need to do, before displaying the results, is count the number of unique dates ('Date') within the listings. For example, if only five days out of the next eight have events happening, I need to know that number is 5.

Using COUNT(DISTINCT) works for giving me that number, but then it only displays one row of results, so I need another solution

My code is this:

$mysqli = new mysqli("Login Stuff Here");
if ($mysqli->connect_errno){
  echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}

$start = strtotime('today midnight');
$stop = strtotime('+1 week');

$start = date('Y-m-d', $start);
$stop = date('Y-m-d', $stop);

$allDates = $mysqli->prepare("SELECT 
    ID,
    Host,
    Type,
    Bands,
    Date,
    Time,
    Price,
    Note,
    Zip,
    URL
    FROM things WHERE (Date >= ? AND Date <= ?) ORDER BY Date, Time, Host");
$allDates->bind_param("ss", $start, $stop);
$allDates->execute();
$allDates->bind_result($ID, $Host, $Type, $Bands, $Date, $Time, $Price, $Note, $Zip, $URL);

while($allDates->fetch()):
  // ECHO ALL THE INFO IN A NICE TABLE
  endwhile;

$allDates->close();

I need to count the unique values (and maybe even retrieve them) from the 'Date' column. Right now I have it working by doing a separate query, but I'm sure there's a better way.

EDIT: Ultimately, I wound up doing a separate query, which worked out well as I was able to use it for other things as well. I found that using GROUP BY always only returned just one result per date, so it didn't work for displaying the full listings. Maybe I was going at it wrong, but I wound up being good in another way. Thanks!

  • 写回答

3条回答 默认 最新

  • douzhi3586 2018-01-23 18:27
    关注

    You are missing group by:

    GROUP BY Date
    
    评论

报告相同问题?

悬赏问题

  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了