When I'm selecting from multiple tables that share column names is there a way I can return both, but define which one I want to select the data from?
For instance:
Both tables contain "date" columns, and I want to use both, but I would like to avoid having to rename each column that has duplicate names.
$query = mysql_query("SELECT * FROM posts, comments"); //(SELECT * is just for example)
while($row=mysql_fetch_array($query))
{
$postDate = $row['date']; //I would like to be able to do something like:
//$postDate = $row['posts']['date']; OR $row['posts.date'];
//of course it's all in an array now, jumbled up.
$commentDate = $row['date'];
}
You need to alias the duplicate column names in your query if you want both, eg
SELECT p.date AS postDate, c.date AS commentDate
FROM posts p, comments c
Then use the aliases to retrieve the values
$postDate = $row['postDate'];
$commentDate = $row['commentDate'];
FYI, it's almost never a good idea to SELECT *, especially when multiple tables are involved. You should always try to be specific about the columns added to your SELECT clause
The best way to do this is to specify the fields in the query itself, giving aliases to them:
SELECT posts.date postDate, comments.date commentDate FROM posts, comments;
It's generally frowned upon to use SELECT *. You end up with code that's a little less stable. By specifying the exact fields, and the aliases of those fields, you are less prone to bugs that might arise from changes to the database schema, etc.
Just add aliases...btw, you should never use SELECT * FROM ...
$query = mysql_query("SELECT posts.date as pdate, comments.date as cdate FROM posts, comments");
while($row=mysql_fetch_array($query))
{
$postDate = $row['pdate'];
$commentDate = $row['cdate'];
}
Related
I have the following two queries. The first query is fetching a key called srNumber from first table called tags and then the second query is using that srNumber to fetch details from a second table called nexttable.
$tagQuery = "SELECT * FROM tags WHERE status = 0 AND currentStage = '1' AND assignedTo = '1' ORDER BY
deliveryDate ASC";
$tagQueryExecute = mysqli_query($conn, $tagQuery);
while($rows = mysqli_fetch_array($tagQueryExecute)){
$srNumber = $rows['srNumber'];
$nextQuery = "SELECT * FROM nexttable WHERE srNumber='$srNumber'";
$nextQueryExecute = mysqli_query($conn, $nextQuery);
$detailsFromNextTable = mysqli_fetch_array($nextQueryExecute);
//Show these details
}
For a small result this is not a big issue. But if the first query got so many results, then second query has to run as many times as number of loop. Is there any other way to do this efficiently?
NB: Please ignore the SQL injection issues with these queries. I just simplified it to show the problem
As you appear to have only 1 row in the second table, you would be better off with a join, MySQL: Quick breakdown of the types of joins gives some more info on the types of joins.
SELECT *
FROM tags t
JOIN nexttable n on t.srNumber = n.srNumber
WHERE t.status = 0 AND t.currentStage = '1' AND t.assignedTo = '1'
ORDER BY t.deliveryDate ASC
This also removes the SQL injection as well.
I would also recommend removing the * and just list the columns you intend to use, this also helps if you have columns with the same names in the different tables as you can add an alias to the specific columns.
FYI - the original problem you have is similar to What is the "N+1 selects problem" in ORM (Object-Relational Mapping)?
Part of my page I have lots of small little queries, probably about 6 altogether, grabbing data from different tables. As an example:
$sql_result = mysql_query("SELECT * FROM votes WHERE voted_on='$p_id' AND vote=1", $db);
$votes_up = mysql_num_rows($sql_result);
$sql_result = mysql_query("SELECT * FROM votes WHERE voted_on='$p_id' AND vote=0", $db);
$votes_down = mysql_num_rows($sql_result);
$sql_result = mysql_query("SELECT * FROM kids WHERE (mother_id='$p_id' OR father_id='$p_id')", $db);
$kids = mysql_num_rows($sql_result);
Would it be better if these were all grabbed in one query to save trips to the database? One query is better than 6 isn't it?
Would it be some kind of JOIN or UNION?
Its not about number of queries but amount of useful datas you transfer. If you are running database on localhost, is better to let sql engine to solve queries instead computing results in additional programs. The same if you are thinking about who should be more bussy. Apache or mysql :)
Of course you can use some conditions:
SELECT catName,
SUM(IF(titles.langID=1, 1, 0)) AS english,
SUM(IF(titles.langID=2, 1, 0)) AS deutsch,
SUM(IF(titles.langID=3, 1, 0)) AS svensk,
SUM(IF(titles.langID=4, 1, 0)) AS norsk,
COUNT(*)
FROM titles, categories, languages
WHERE titles.catID = categories.catID
AND titles.langID = languages.
example used from MYSQL Bible :)
If you really want to lower the number of queries, you can put the first two together like this:
$sql_result = mysql_query("SELECT * FROM votes WHERE voted_on='$p_id'", $db);
while ($row = mysql_fetch_array($sql_result))
{
extract($row);
if ($vote=='0') ++$votes_up; else ++$votes_down;
}
The idea of joining tables is that these tables are expected to have something in between (a relation, for example).
Same is for the UNION SELECTS, which are prefered to be avoided.
If you want your solution to be clean and scalable in future, I suggest you to use mysqli, instead of mysql module of PHP.
Refer to: mysqli::multi_query. There is OOP variant, where you create mysqli object and call the function as method.
Then, your query should look like:
// I use ; as the default separator of queries, but it might be different in your case.
// The above could be set with sql statement: DELIMITER ;
$query = "
SELECT * FROM votes WHERE voted_on='$p_id' AND vote=1;
SELECT * FROM votes WHERE voted_on='$p_id' AND vote=0;
SELECT * FROM kids WHERE (mother_id='$p_id' OR father_id='$p_id');
";
$results = mysqli_multi_query($db, $query); // Returns an array of results
Fewer queries are (generally, not always) better, but it's also about keeping your code clear enough that others can understand the query. For example, in the code you provided, keep the first two together, and leave the last one separate.
$sql_result = mysql_query("SELECT vote, COUNT(*) AS vote_count
FROM votes
WHERE voted_on='$p_id'
GROUP BY vote", $db);
The above will return to you two rows, each containing the vote value (0 or 1) and the vote count for the value.
I have mysql table tmp with columns pid,city,state,country. I write queries so i can find matching city,state or country, and pid is field that helps me load another table.
The thing is, there is always two rows with same pid, and sometimes (when WHERE find matching city state or country in both), i display data from additional table twice unnecessarily.
So i need to select something like:
SELECT * FROM tmp DISTINCT pid WHERE city='test'
I have no idea how to search solution (i searched here on stackoverflow, but no luck).
Also, there will be a lot of searching in this table, so if there is multiple solutions i would prefer one that is faster.
Thanks
Please try the following SQL statement:
SELECT DISTINCT pid FROM tmp WHERE city='test'
try this
SELECT DISTINCT pid,field1,field2 FROM tmp WHERE city='test'
$keyword="0";
$query = "SELECT DISTINCT titel,id FROM xyz ORDER BY titel ASC ";
$result = mysql_query($query);
while ($row = mysql_fetch_array($result))
{
if($keyword!==$row["titel"])
{
$keyword=$row["titel"];
echo $keyword;
}
}
I'm creating a feed by retrieving information from my database using nested while loops (is there a better way to do this?).
I have one table called users with all the names amongst other things. The other table is called messages which has messages, the user who posted it, and a timestamp.
$userQuery = mysql_query("SELECT name FROM users");
while ($user = mysql_fetch_array($userQuery, MYSQL_NUM)) {
$messageQuery = mysql_query("SELECT message FROM messages WHERE user = $user ORDER BY timestamp DESC");
while ($message = mysql_fetch_array($messageQuery, MYSQL_NUM)) {
echo "$user[0]: $message[0]";
}
}
The problem is that it doesn't order by the timestamp and I can't tell how it's ordered. I've tried timestamp, datetime, and int types with UNIX timestamps.
EDIT: I should add that the user and message matches up fine, it's just the ordering that doesn't work.
I guess you get your users in more or less random order and "within" one user the sorting is ok?!
use:
$result = mysql_query('select users.name,messages.message from messages join users on (users.name=messages.user) order by messages.timestamp');
while($row = mysql_fetch_row($result))
echo "$row[0]: $row[1]";
That should give you an ordered result (at least if you have a column called messages.timestamp. Check the name ;-)). And all in one query...
For the query, you could create a join
SELECT u.name as name, m.message as message
FROM users u inner join messages m
on u.user = m.user
order by
m.timestamp DESC
As for the second part, I don't see anything wrong with your could. May be you could post some samples of your data to see if that is making any difference.
Hey guys, I created a list for fixtures.
$result = mysql_query("SELECT date FROM ".TBL_FIXTURES." WHERE compname = '$comp_name' GROUP BY date");
$i = 1;
$d = "Start";
while ($row = mysql_fetch_assoc($result))
{
$odate = $row['date'];
$date=date("F j Y", $row['date']);
echo "<p>Fixture $i - $d to $date</p>";
}
As you can see from the query, the date is displayed from the fixtures table.
The way my system works is that when a fixture is "played", it is removed from this table. Therefore when the entire round of fixtures are complete, there wont be any dates for that round in this table. They will be in another table.
Is there anyway I can run an other query for dates at the same time, and display only dates from the fixtures table if there isnt a date in the results table?
"SELECT * FROM ".TBL_CONF_RESULTS."
WHERE compid = '$_GET[id]' && type2 = '2' ORDER BY date"
That would be the second query!
EDIT FROM HERE ONWARDS...
Is there anyway I can select the date from two tables and then only use one if there are matches. Then use the rows of dates (GROUPED BY) to populate my query? Is that possible?
It sounds like you want to UNION the two result sets, akin to the following:
SELECT f.date FROM tbl_fixtures f
WHERE f.compname = '$comp_name'
UNION SELECT r.date FROM tbl_conf_results r
WHERE r.compid = '$_GET[id]' AND r.type2 = '2'
GROUP BY date
This should select f.date and add rows from r.date that aren't already in the result set (at least this is the behaviour with T-SQL). Apparently it may not scale well, but there are many blogs on that (search: UNION T-SQL).
From the notes on this page:
//performs the query
$result = mysql_query(...);
$num_rows = mysql_num_rows($result);
//if query result is empty, returns NULL, otherwise,
//returns an array containing the selected fields and their values
if($num_rows == NULL)
{
// Do the other query
}
else
{
// Do your stuff as now
}
WHERE compid = '$_GET[id]' presents an oportunity for SQL Injection.
Are TBL_FIXTURES and TBL_CONF_RESULTS supposed to read $TBL_FIXTURES and $TBL_CONF_RESULTS?
ChrisF has the solution!
One other thing you might think about is whether it is necessary to do a delete and move to another table. A common way to solve this type of challenge is to include a status field for each record, then rather than just querying for "all" you query for all where status = "x". For example, 1 might be "staging", 2 might be "in use", 3 might be "used" or "archived" In your example, rather than deleting the field and "moving" the record to another table (which would also have to happen in the foreach loop, one would assume) you could simply update the status field to the next status.
So, you'd eliminate the need for an additional table, remove one additional database hit per record, and theoretically improve the performance of your application.
Seems like what you want is a UNION query.
$q1 = "SELECT DISTINCT date FROM ".TBL_FIXTURES." WHERE compname = '$comp_name'";
$q2 = "SELECT DISTINCT date FROM ".TBL_CONF_RESULTS.
"WHERE compid = '$_GET[id]' && type2 = '2'";
$q = "($q1) UNION DISTINCT ($q2) ORDER BY date";