Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7703125
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 31, 20262026-05-31T23:23:12+00:00 2026-05-31T23:23:12+00:00

I’m writing code in which I use SQL to test several different conditions before

  • 0

I’m writing code in which I use SQL to test several different conditions before ultimately deciding what to do. I’m trying to decide between writing a single multipart MySQL query, or writing one query for each condition, with PHP handling the logic of combining them. My questions:

  1. Are there any good practices or pitfalls that should steer me in either direction?
  2. If I implement all the logic in a single SQL query, can I get it to return information about how each condition turned out? (see below for explanation.)

Here’s a simplified example. I want to look at how long it’s been since a user has visited the website, and finds an appropriate reminder email to send them. We test 3 independent conditions:

  1. Which email(s) should be sent based on the time since the user’s last visit?
  2. For each of those emails, has the user not received this email before?
  3. Has the user not received any emails from us in the past 3 days?

Here’s an SQL query that checks all 3 of those. (this query is done per user; it uses PDO and variables starting with : are bound parameters):

SELECT message_id, message_content FROM emailtemplates
WHERE time_before_reminder < :days_since_visit
AND message_id not in 
    (SELECT message_id FROM sentemails WHERE user = :userid)
AND :userid not in 
    (SELECT userid FROM sentemails WHERE date_add(timesent, interval 3 day) >= now())
ORDER BY time_before_reminder asc
LIMIT 1;

It returns zero rows if any of the conditions fails, or one row if they all pass.

Alternately, here’s some code that does several separate queries. It’s much uglier, but it can give me explanatory output about precisely why we’re not emailing a given user. (I’ve switched to pseudocode so you don’t have to read a zillion $stmt->bindParam($params) lines):

//run the query for condition 1:
query("SELECT message_id, message_content FROM emailtemplates WHERE time_before_reminder < :days_since_visit;")
if 0 rows returned:
    echo("no appropriate emails found for this participant")
    return false

//then for condition 2:
query("SELECT message_id from sentemails where message_id = :msgid AND user = :userid")
if 1 or more rows returned:
    echo("user $userid qualified for message $msgid, but they already received it.");
    return false

//then for condition 3:
query("SELECT userid FROM sentemails WHERE user = :userid AND date_add(timesent, interval 3 day) >= now();")
if 1 or more rows returned:
    echo("user $userid qualified for message $msgid, but they already received an email from us in the past 3 days. No email sent.")
    return false

// if we get here, all tests were passed. Send the message that was found in the first query.
send_reminder($userid, $msgid)
echo("successfully sent message $msgid to user $userid!")
return true

The second example seems really cumbersome, but I like finding out exactly which condition failed and why. Is there a way to have a single query return this kind of information? (I mean returning information that can be parsed into an explanation, of course, not having MySQL write English sentences for me.) Or, is there other advice on handling queries that test several independent conditions like this?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-31T23:23:14+00:00Added an answer on May 31, 2026 at 11:23 pm

    You can probably (tested on MySQL 5.5 without bound parameters) use your conditions in the SELECT clause, they should come out 0 (failed) or 1 (passed):

    SELECT
        message_id, 
        message_content, 
        (time_before_reminder < :days_since_visit) AS time, 
        (message_id NOT IN (SELECT message_id FROM sentemails WHERE user = :userid)) AS already, 
        (:userid NOT IN (SELECT userid FROM sentemails WHERE date_add(timesent, interval 3 day) >= now())) AS recent 
    FROM emailtemplates
    WHERE time_before_reminder < :days_since_visit
    AND message_id not in 
        (SELECT message_id FROM sentemails WHERE user = :userid)
    AND :userid not in 
        (SELECT userid FROM sentemails WHERE date_add(timesent, interval 3 day) >= now())
    ORDER BY time_before_reminder asc
    LIMIT 1;
    

    However, I suppose this means twice the work for the DBMS. It must also be possible to use some LEFT JOIN and see what fields are null… and that’d be more elegant, and probably faster too.

    Another thing – though irrelevant for your question – what’s the point having an ORDER BY followed by a LIMIT 1 ?

    Edit: the LEFT JOIN-based request should be something like this (tell me if it works, I can’t test it unless I create the DB… and I feel lazy ^^):

    SELECT
      et.message_id AS messageId, 
      et.message_content AS messageContent, 
      se1.message_id AS nullIfNotSent, 
      se2.userid AS nullIfMoreThan3Days 
    FROM 
      (SELECT :userid AS userid) AS param
        LEFT JOIN sentemails AS se2 
          ON param.userid=se2.userid AND date_add(se2.timesent, interval 3 days) >= now(),
      emailtemplates AS et
        LEFT JOIN sentemails AS se1 
          ON et.message_id=se1.message_id AND se1.userid=param.userid
    WHERE 
      time_before_reminder < :days_since_visit
    ORDER BY time_before_reminder 
    LIMIT 1;
    

    Expected behavior: zero rows returned means it failed the first test (time_before_reminder), otherwise if nullIfNotSent is not null (therefore a valid message_id) it means it failed the second test (this kind of message has already been sent someday), and if nullIfMoreThan3days is not null (a valid user ID) it means the user already received a message in the past 3 days (i.e. failed the third test). So if you get a row with nullIfNotSent and nullIfMoreThan3Days, it means you can send a message using the returned messageId and messageContent.

    Please tell if it does work! (or doesn’t) 😉

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I am trying to understand how to use SyndicationItem to display feed which is
I'm trying to use string.replace('’','') to replace the dreaded weird single-quote character: ’ (aka
link Im having trouble converting the html entites into html characters, (&# 8217;) i
I used javascript for loading a picture on my website depending on which small
Basically, what I'm trying to create is a page of div tags, each has
I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
I have this code to decode numeric html entities to the UTF8 equivalent character.
I want use html5's new tag to play a wav file (currently only supported
I am trying to render a haml file in a javascript response like so:
I would like to run a str_replace or preg_replace which looks for certain words

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.