Tracking Forums, Newsgroups, Maling Lists
Home Scripts Tutorials Tracker Forums
 
  HOME    TRACKER    MYSQL




Can You Use "UNIX_TIMESTAMP" Outside The Mysql Query?


Hey guys. I was using this code:

mysql_connect($dbhost, $dbuser, $dbpassword) or die("Couldn't connect to server.");
@mysql_select_db($dbname) or die("Couldn't connect to database.");

$q="SELECT poker_room,game_type,limit_type,UNIX_TIMESTAMP(date_time),date_time,buyin_desc,description,url FROM poker_tourneys ORDER BY date_time ASC";
$sql=mysql_query($q);
$num=mysql_num_rows($sql);

mysql_close();

Then using this code to get the results:

while (list($poker_room,$game_type,$limit_type,$dt,$dt2,$buyin_desc,$description,$url)=mysql_fetch_array($ sql)) {
// Blah
}

But I need to only display certain results so depending on the page they are on.. so I was wanting to get each results values with the "mysql_result()" funtion; but I can't figure out how to get the UNIX_TIMESTAMP to work this way.....




View Complete Forum Thread with Replies

See Related Forum Messages: Follow the Links Below to View Complete Thread
Single Query For No Of Hits "Today", "This Month", "This Year"
Is it possible to construct a single query that fetches the no of pageviews "today", "this month", "this year" and "total since start"?

The table is very simple, one field for Date (YYYY-MM-DD) and one for the no of pageviews this day.

If not, would it be much slower/faster to divide the query into 4 different queries?

Relations In "CASCADE", "SET NULL", "NO ACTION", "RESTRICT", "--" ?
what do they mean to set the relations of a Foreign KEY in "CASCADE", "SET NULL", "NO ACTION", "RESTRICT", "--" ?

REQ: MySQL 4.0 Equivilent Of "DateDiff("m", Date, Now())=1"
I have a query that works in the rest of the SQL world

"SELECT invoice.*, invoice.Date
FROM invoice
WHERE (DateDiff("m", Date, Now())=1);"

which will give me all of last month's invoices.

However it doesn't work with MySQL 4.0.

While

"SELECT
Invoice.*
FROM
invoice
WHERE
(Month(Invoice.Date) = ((Month(Now()))-1))"

Is a close substituent, it will blowup in January.

Anyone have an equivalent expression for MySQL 4.0?

What Is Execution Time Of A Query Based On? (was "a Mysql Question")
when selecting data from the database, does the time taken to retrieve it vary from 56k connections to T3 connections? or does it all depends ont he general server speed/amount of connections on the db?

im not sure if ive explained that in the best way for people to understand
but im sure someone will get what i mean

Adjacent Theater Seats (was "mySQL Query Issue")
Having not been working with more than a simple SELECT * from table query, I am having a few issues when it comes to using more complex queries.

I am currently using a query to select seats from a database using the following query:

$query1 = mysql_query("SELECT struct.seatid, struct.row, struct.seatnum FROM seats as seat LEFT JOIN structure as struct USING (seatid) WHERE seat.showtimeid=".(int) $_GET['id']." && seat.available = &#391;' && seat.timelimit < $minutes2 ORDER BY seat.seatid ASC");
For each record that is selected I want to check if either of the seats either side of it are also selected, if not then it is not to be shown.

I have added a while loop below the above query and run another query following it (not sure if that makes sense, so I will paste it below!)

while($rows = mysql_fetch_assoc($query1)){

$minusseat = $rows[seatid] - 1;
$plusseat = $rows[seatid] + 1;

$queryminusseat = mysql_query("SELECT * from seats LEFT JOIN structure WHERE seat.showtimeid=".(int) $_GET['id']." && seat.available = &#391;' && seat.seatid == $minusseat && seat.timelimit < $minutes2");

$num_rows = mysql_num_rows($queryminusseat)or die(mysql_error());

echo "$num_rows";

//if($minusnum > 0){
//echo "$minusseat <b>" . $rows[seatid] ."</b> $plusseat <br/>";
//} else {
//echo "<font color=red>$minusseat <b>" . $rows[seatid] ."</b> $plusseat <br/></font>";
//}

}
The code above is used below the initial query and the following error is being displayed:

Quote:

Warning: mysql_num_rows(): supplied argument is not a valid MySQL result resource in C:Program Filesxampphtdocsprojectprototype1 ickets.php on line 154
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE seat.showtimeid=1 && seat.available = &#391;' && seat.seatid == 1 && seat.time' at line 1

User_id And Password Error? (was "mysql Query")
Following Query right or not

$sql = "SELECT * FROM login WHERE user_id = ".$username." AND password = ".$passwd."";

if error then point out error


Next And Prev DisplayOrder Values (was "Help With MySQL Query")
I have a table 'Album' containing columns 'PageID' and 'DisplayOrder' (both INT).
On each page that is displayed I want to have 'previous' and 'next' links to other pages, which are arranged via the DisplayOrder column.

At the moment I'm doing this in 2 separate queries:

SELECT DisplayOrder FROM Album WHERE PageID = $currentPage
$currentNo = [result of last query]
SELECT PageID FROM Album WHERE DisplayOrder IN ($currentNo-1, $currentNo+1)
Highly simplified but you get the idea. Would it be possible to combine this into one query?

Script To Change All Columns (was "mysql Query")
I have a table. I need to make some changes like change column name, change int() to var() etc. So I want to write a query that alter all the columns of the table then the data which were in the database before can be reinserted.

"Lost Connection To MySQL Server During Query"
Bog standard SuSE 8.2 Linux install.

I have installed mySQL (off the SuSE 8.2 distro CDs). I can connect locally,
e.g:

bealzebub> mysql -u root -p mysql -h localhost

....logs me in just fine. However, this:

bealzebub> mysql -u root -p mysql -h bealzebub

....causes the connection to fail with: "ERROR 2013: Lost connection to MySQL
server during query". Its the same if I try to log in from another machine.

"Lost Connection To MySQL Server During Query"
Hi, I wonder if anyone can help me with this.

Bog standard SuSE 8.2 Linux install.

I have installed mySQL (off the SuSE 8.2 distro CDs). I can connect locally,
e.g:

bealzebub> mysql -u root -p mysql -h localhost

....logs me in just fine. However, this:

bealzebub> mysql -u root -p mysql -h bealzebub

....causes the connection to fail with: "ERROR 2013: Lost connection to MySQL
server during query". Its the same if I try to log in from another machine.

Anyone?

Not Sure How To Use Inner Join (was "MySQL Query Help Please...")
Basically i have 2 tables users and listings. In users table there is user's info like username / password etc. and in listings table there are listings of a user..which can be more than 1.

Currently I was just getting results by just searching the listings table by a simple query like: "SELECT * FROM listings WHERE title = 'abc'"; but now what I want do is that I can search for some fields in user table also.

For eg. currently listings are displayed..but now i should be able to see all listings by searching username of post code. So please tell me how do i go about it ? I know that it can be done using INNER JOIN but i am not sure how to use it.

Searching For Numbers - &quot;close To&quot; Or &quot;approximate&quot;
I would like to know how to search a table for records where a particular field is "close to" a particular number.

For instance, let's say I have a table containing students and their most recent test scores. I'd like to see students who scored 7/10. That's easy enough (select * from table where score = 7). I'd also like to run another query to identify other students whose scores are not 7 but "close to" 7. Ie students who scored 6 or 8.

As an added bonus, I'd like to be able to do a related search that shows students who scored 7, then shows the other students ordered by how "close" they are to 7. Ie students who scored 6 or 8 are "closest" matches, and students who scored 1 are "furthest". I hope this makes sense!

Is there any pre-existing MySQL command that will do this? Or will I have to run separate queries for each value?

Create Single Query From Queries On Two Tables (was "Help With Query...")
I read from other thread that query inside loop is not good idea. May I ask some help how can I create a single query to the following code which I use loop.

$sql = "SELECT * FROM mytable order by points desc limit 10";
$rec = mysql_query($sql) or die(mysql_error());
$datas = mysql_fetch_array($rec);

do{
$sq = "Select * from secondtable where linkid = '$datas[id]'";
$rst = mysql_query($sq) or die(mysql_error());
$rows = mysql_fetch_array($rst);
echo "$rows[somefield]";
}while($datas= mysql_fetch_array($rec));
This works perfectly but I want the second query to be out of the loop if there is a way and how.

Grab 'title' From The Table 'forum' Within The Same Query (was "Help With Query")
I have the following query for my vBulletin database:
PHP

$get_stats_newthreads = $db->query_read("    SELECT thread.forumid, thread.postuserid, thread.postusername, thread.threadid, thread.title, thread.lastpost, thread.forumid, thread.replycount, thread.lastposter, thread.dateline, thread.iconid, thread.views, IF(views<=replycount, replycount+1, views) AS views, thread.visible    FROM " . TABLE_PREFIX . "thread AS thread    WHERE NOT ISNULL(thread.threadid) AND $weekold<lastpost AND thread.visible!=0 AND (forumid=34 OR forumid=7 OR forumid=8 OR forumid=11 OR forumid=10)    ORDER BY rand() DESC LIMIT 5");

and would like to grab 'title' from the table 'forum' where forum.forumid=thread.forumid

Design For Stock Items And Checkin/checkout Process (was "Query Help")
I'm currently in the process of trying to bodge together a simple(ish) stock system to be used on a company intranet but I've ground to a halt with a particular problem.

Using a MySQL database I've got tables with 11 fields, including 'Quantity' (self explanatory) and BookOut. Now this BookOut field contains information on the user who has booked out an item including the users name, the date/time etc

The problem I have is this. If an item has a quantity of 7 and a user books out 1, then his/her info is stored in BookOut but when another user books out another 1 of said item at a later stage then the previous BookOut info is overwritten.

Is there a way in that everytime another item is booked out that a new line is created within a specific field?

}

if(!sizeof($error)){

$update_SQL = "Update joystick Set BookOut = '" . mysql_real_escape_string($BookOut) . "', PCserial = '" . mysql_real_escape_string($PCserial) . "', Quantity = Quantity - " . $Quantity . ", MachineNo = '" . mysql_real_escape_string($MachineNo) . "', Date = now() WHERE ID = " . $ID;
if(! @mysql_query($update_SQL)){

$error[] = "Update SQL failed";

}
The above is the query I am currently using. I'm not totally proficient with .php and have already had a lot of help getting this far.

Query To Populate A Calendar (was "Wanted The Experts Opinions (that Means YOU!)")
I am building my first calendar for a client to list All their events on a month to month basis.

There are several tables of data that I need to query to populat the calendar from: Events, Committee Meetings, Lectures, and Group Actions.

I was wondering:

#1) Is it more effecient to query all the tables once and to store the results into an array that I can check as I loop through and output the days for the calendar?

#2) OR, is it better to query all the tables for each day as I loop through and construct the calendar ouput?

After formulating my question it seems like a no-brainer: That option #1 would be the most effecient, but I still would like to know your opinions. Especially if you have made a calendar before.

List All Clients Not Assigned To Current User (was "Query Help Please")
I have two tables like this:

*clients
-- client_id
-- client_name

*manage
-- user_id (multiple entries possible)
-- client_id

To assign clients to users there is a entry in the manage table of the
user_id and client id.

I want to list all the client_ids and client_names that are not assigned to the current user_id say 1.

Unique Combinations Of Model And Make (was "Query Question")
I'm trying to write a query and was wondering if someone could help me formulate it. Here is an example table I'm working with:

Table: vehicles
Model Make
Ford Taurus
Ford Taurus
Ford F150
Chevy Tahoe
Chevy Blazer
Chevy Tahoe

I want a query that returns all unique combinations of model and make. So the result set should be:
Model Make
Ford Taurus
Ford F150
Chevy Blazer
Chevy Tahoe

I know how to return distinct values for one variable, but not for two like that. Any help is greatly appreciated.

Count Query Causing &quot;excessive Processor Usage&quot;
For the second time in the past 6 months my hosts have shut down my site because it was apparently causing a shared mySQL 5 server to max out at 100% usage. I'm not much a programmer, know even less about mySQL and obviously don't have access to the server from the back end but I'd appreciate any advice as to whether it is my query that is causing the problem:

Set rsMail = objConnC.Execute("SELECT * ,(SELECT COUNT(*) FROM comments WHERE comments.submissionID = submissions.submissionID AND comments.commentInclude = 1) as CommentCount FROM submissions WHERE PigeonHole = 'mailbag' AND Status <> 'hold' ORDER BY submissionID DESC LIMIT 20")

Apart from two instances, this query has been working fine on a page that receives between 10,000 and 30,000 visits a day.

The site is running on Windows and coded in ASP but is calling a separate mySQL server.

Invalid Use Of Group Function (was "Baffled By Query Error")
trying to figure out why I keep getting this error with the following query:

SELECT c.account_id,a.name,a.company,SUM(c.agent_product_time) AS mins
FROM account a LEFT JOIN calls c ON c.account_id = a.id
WHERE c.calldate >= DATE_SUB(NOW(),INTERVAL 14 DAY) AND c.agent_id = 2
AND SUM(c.agent_product_time) >= '500' GROUP BY c.account_id ORDER BY mins

ERROR: #1111 - Invalid use of group function

Most Products Flagged In The Past 24 Hours (was "Query Help")
I need a little help setting up the logic behind a query. Here is the situation:

I have 2 tables. Product table. Flag table (flagID, productID, date_flagged). Users can flag products. *date_flagged is a INTEGER unix timestamp.

I would like to be able to setup a query where I can pull up products that have been flagged the most in the past 24 hours.

At first I figured I would COUNT() the flags and GROUP BY productID, but this of course will only give me the most flagged all time, and because of the grouping by productID will not allow me to filter it by date.

Delete Except Latest 2500 Entries (was "help With Query")
I have a table that holds information on activities.
For each activity I store the following:
ID, When, Description
The ID is the key for the table
The When column holds the datetime when the activity was added

The table gets filled up pretty quickly.
I would like to run a query that will delete ALL the entries except for the 2500 latest ones. The When column should be the one to use when deciding which are the 2500 latest activities

Can someone show me the most efficient way of doing this?



Count User Comments In Each Category (was "help On A Query")
I would really appreciate if someone could help me out on this one. this are my tables:

comments

Comment_ID
Video_ID
Comment_Text
Comment_UserID
....
video
Video_ID
Category_ID
.....
category
Category_ID
Category_Name

I'm trying to get a user's count of comments for each category, ordered by the number of comments DESC. basically, I want to show the top categories where the user has posted the highest number of comments.

so far this query gets me the category name of where the user has posted:


PHP

$SQLTemp = "SELECT Category_Name
            FROM category
            WHERE Category_ID
            IN (
            
            SELECT DISTINCT (    Category_ID        )
            FROM video
            WHERE Video_ID
            IN (
            
            SELECT DISTINCT (    Video_ID        )
            FROM comments
            WHERE Comment_UserID = $id
            )
            )";

THANKS!!

Count Of *unique* Visits By Page For Each Day (was "Need Help With Query")
Using MySQL 4.1

I have a table 'orders' with the following fields:
ipaddress
pagenum
xtime (which is just the yearmonthday)

this is the query:
SELECT distinct pagenum,ipaddress,xtime,count(pagenum) AS pagenumtotal FROM `orders` group by pagenum,xtime ORDER by xtime, pagenum asc

What I am trying to do is return a count of *unique* visits by page for each day. This query returns a count of *all* visits by page for each day, including repeats. So if a visitors hits a certain page on the site 10 times and adds a record 10 times, the count result will include all 10 records in the count. I want this to only count as 1.

Find All Games A User Has A Top 3 Score In (was "Need Help With A Query")
I am trying to create a query that will go through a scores table for me and find all the games that a user has a top 3 score in. Here are the table that are relevant I think...

CREATE TABLE files (
fileid int(11) NOT NULL auto_increment,
file text NOT NULL,
icon text NOT NULL,
filelocation int(1) NOT NULL default &#391;',
iconlocation int(1) NOT NULL default &#391;',
customcode text NOT NULL,
title text NOT NULL,
description text NOT NULL,
keywords text NOT NULL,
width int(11) NOT NULL default &#390;',
height int(11) NOT NULL default &#390;',
category int(11) NOT NULL default &#390;',
timesplayed int(11) NOT NULL default &#390;',
status int(1) NOT NULL default &#390;',
filetype int(2) NOT NULL default &#390;',
dateadded date NOT NULL default &#55612;&#57200;-00-00',
rating int(11) NOT NULL default &#390;',
totalvotes int(11) NOT NULL default &#390;',
totalvotepoints int(11) NOT NULL default &#390;',
scores enum(&#390;',&#391;') NOT NULL default &#390;',
PRIMARY KEY (fileid)
) TYPE=MyISAM AUTO_INCREMENT=2285 ;

CREATE TABLE scores (
scoreid int(11) NOT NULL auto_increment,
fileid int(11) NOT NULL default &#390;',
score int(11) NOT NULL default &#390;',
username text NOT NULL,
userid int(11) NOT NULL default &#390;',
usercomment text NOT NULL,
dateadded date NOT NULL default &#55612;&#57200;-00-00',
PRIMARY KEY (scoreid)
) TYPE=MyISAM AUTO_INCREMENT=16 ;

CREATE TABLE users (
userid int(11) NOT NULL auto_increment,
username text NOT NULL,
password text NOT NULL,
email text NOT NULL,
status enum(&#391;',&#390;') NOT NULL default &#390;',
usergroup int(11) NOT NULL default &#391;',
joined date NOT NULL default &#55612;&#57200;-00-00',
played int(11) NOT NULL default &#390;',
comments int(11) NOT NULL default &#390;',
avatar text NOT NULL,
avatar_uploaded enum(&#391;',&#390;') NOT NULL default &#390;',
location text NOT NULL,
website text NOT NULL,
gender int(1) NOT NULL default &#390;',
favourite int(11) NOT NULL default &#390;',
receiveemails enum(&#391;',&#390;') NOT NULL default &#391;',
newpm enum(&#391;',&#390;') NOT NULL default &#390;',
confirmation text NOT NULL,
PRIMARY KEY (userid)
) TYPE=MyISAM AUTO_INCREMENT=8 ;
(
Basically the query would need to search through the scores table to find if the specified user $userid has the top 3 (by top 3 i mean 1st, 2nd, or 3rd highest score) scores of any game in the scores table. The end resukt would be a list that contained the fileid of the game the user has a top 3 score in, the actual score, and the position (1, 2, or 3) Im not sure if I am even explaining this right cause im kind of tired. I am a novice MYSQL user but this just has me stumped

Models Where The Years Overlap (was "Query Help Needed")
I'm trying to formulate a query for the following example:

Table: model_by_year
model start_year end_year
model_1 2001 2004
model_1 2003 2004
model_2 2000 2005
model_2 1998 1999
model_3 1998 2003
model_3 2002 2006

I want a query that will return all like models where the years overlap. In other words, I'd want to return model_1 and model_3, but not model_2.

Dates In The Past 3 Weeks (was "SELECT Query Help")
I'm trying to select data from a table that has been submitted in the past 3 weeks. I am not having any success.

How To Get The Total Number Of Rows With A Query "limit" ?
I would like to paginate the results of a query on several pages. So I
use a query with a limit X offset Y to display X results on a page,
ok.

But for the first page, I need to run the same query with a count(*)
to know how many pages I will get (number total of rows/ X).

The problem is my query is very slow (maybe 5s) because there is much
worch to do, and on the first page, I need to run this query twice
(not exactly, but ...) so the page is very very slow to load.

My question is : is there a function to get the total number of rows
even on a query with "limit" ? Or what could I do else?

How To Get The Total Number Of Rows With A Query "limit" ?
I would like to paginate the results of a query on several pages. So I
use a query with a limit X offset Y to display X results on a page,
ok.

But for the first page, I need to run the same query with a count(*)
to know how many pages I will get (number total of rows/ X).

The problem is my query is very slow (maybe 5s) because there is much
worch to do, and on the first page, I need to run this query twice
(not exactly, but ...) so the page is very very slow to load.

My question is : is there a function to get the total number of rows
even on a query with "limit" ? Or what could I do else ?

How To Get The Total Number Of Rows With A Query "limit" ?
I would like to paginate the results of a query on several pages. So I
use a query with a limit X offset Y to display X results on a page,
ok.

But for the first page, I need to run the same query with a count(*)
to know how many pages I will get (number total of rows/ X).

The problem is my query is very slow (maybe 5s) because there is much
worch to do, and on the first page, I need to run this query twice
(not exactly, but ...) so the page is very very slow to load.

My question is : is there a function to get the total number of rows
even on a query with "limit" ? Or what could I do else ?

Value &quot;000&quot; Stored As &quot;0&quot; In Text Field?
I've managed to import my data from a CSV using SQLyog Enterprise, however, I have a problem with the table storing the text value "000", MySQL truncates it to "0", unfortunately, I need the value to be stored as "000", does anyone know of any way that I can force the field to store all the characters, rather than treating it as a number? Surely a text field should treat any numbers stored within it as text?

Return A &quot;true&quot; Or &quot;false&quot;
i wanna do a "select", where if the script finds any matches, i dont wanna know about them. Instead, i just want it to return a a value: true (1) ou false (0).

ie.:

$sth = $dbh->prepare("SELECT * FROM maps WHERE name='algo' LIMIT 1");
$sth->execute();

if (match is true) {
print "True Match. A match was found";
}
else {
print "False Match. No matches were found.";
}

"Group By" Forgets "Order By"
I'm trying to build a simple RSS reader for a client and am running into some serious problems with the GROUP BY in MySQL. Basically I have two tables: one that holds all the entries and one that holds all the feeds. Then what I can do is say:
[MYSQL]SELECT * FROM entries WHERE feed_id='13' ORDER BY date DESC[/MYSQL]
That will select all the entries that belong to feed #13. This is fine, but what I'm doing now is building a library that will display the feed_id with the latest entry with that id. So I would think it would be something like the following:
[MYSQL]SELECT * FROM entries GROUP BY feed_id ORDER BY date DESC[/MYSQL]
That should get me the single latest entry from each feed_id. However it's forgetting the ORDER BY clause all together and seemingly ordering it by the auto-incrememnt value in the entries field.

Return Only 3 Photos From 3 Specified Galleries In One Query (was "Is It Possible?")
Let me start from the beginning.... I have a table that lists photo details, with a foreign key to link them to a gallery. Lets say I have 20 photos altogether and 4 galleries, (for simplicity sake, 5 photos per gallery).

My question is:

Is it possible to query the table to get it to return only 3 photos from 3 specified galleries in one query? (So returning 9 photos altogether, 3 from each gallery) Rather than querying the table 3 times with a limit of 3 and merging the results.

Want Only One Record Returned Per Post_id (was "Help With Query")
I can't figure out how to do this query. Help would be muchly appreciated!

I want to get the DISTINCT(post.post_id) but not sure how to do this.

Here is the query I have thus far but it's returning two records each with the same post_id but different cat_id's.

SELECT post.post_id, auth_alias, pc.cat_id, post_heading, DATE_FORMAT(post_created, '%M %d, %Y'), post_body FROM posting post LEFT OUTER JOIN post_cats pc ON post.post_id = pc.post_id WHERE post_status = &#391;' ORDER BY post.post_created DESC LIMIT 0,5

SUM(price*quantity) Not Very Accurate (was "Query HElp")
Query-Geek is back with some anoying problems, so bear with me!! hahaha

i have tbl1 with category_id,price,quantity. tbl2 has total.

now want to create a query that will do this

select SUM(price*quantity) as total from tbl1 where category_id=1
well obviously you know what i mean..all similar category_id will have first, multiply price to quantity, then all of those should be summed up.. then save that to tbl2.

Incorporate An Additional WHERE Condition (was "Help With My Query Please?")
I’m trying to incorporate an additional statement in the below query, which works:

$sql = "SELECT b.bookID, b.roomID, b.arrive, b.depart, b.status, b.property_id
FROM room_booking_two b
WHERE ((b.arrive BETWEEN '$d1' AND '$d2') OR
(b.depart BETWEEN '$d1' AND '$d2'))
ORDER BY b.roomID, b.arrive";
Now I want to add the line:

WHERE b.property_id=".$_GET['property_id'])
So I thought it would work like this:

$sql = "SELECT b.bookID, b.roomID, b.arrive, b.depart, b.status, b.property_id
FROM room_booking_two b
WHERE b.property_id=".$_GET['property_id'])
AND ((b.arrive BETWEEN '$d1' AND '$d2') OR
(b.depart BETWEEN '$d1' AND '$d2'))
ORDER BY b.roomID, b.arrive";
But that does not seem to work. Can anyone please advise?

Do The ORs Mess Up My Results? (was "query Problem")
SELECT score, comments, job_number, fname, lname, account_name FROM feedback_reports
LEFT JOIN sales_reps ON sales_reps.sr_id = feedback_reports.sr_id
LEFT JOIN shop_assignments ON shop_assignments.sr_id=sales_reps.sr_id
LEFT JOIN users ON users.user_id=feedback_reports.user_id
LEFT JOIN accounts ON accounts.account_id=users.account_id
WHERE LOWER(job_number)='mh_midwest_tt_03032007'
OR LOWER(fname) like '%mh_midwest_tt_03032007%'
OR LOWER(lname) like '%mh_midwest_tt_03032007%'
OR score='mh_midwest_tt_03032007'
AND account_name='PI'
My results are including records that don't have account_name='PI'

Do the ORs mess that up?

Sellers Without Referenced Property Should Also Appear (was "SQL Query Help")
I have a query that joins 3 tables, one holding property details, one holding sellers details, and one holding an activity log of every operation performed.

The query to list the sellers looks like this

SELECT Agents_Prop_Code, sell_t.Sellers_ID, Seller_1_Prename, Seller_1_Surname, Address_Town, Tel_No, Mob_No, Seller_2_Prename, Seller_2_Surname, Email_Add, prop_t.Prop_ID, Address_Town, MAX(activity_t.Date) AS lastcomm

FROM sell_t

INNER JOIN prop_t
ON sell_t.Sellers_ID = prop_t.Sellers_ID
AND sell_t.Agency_Code =&#391;'
AND sell_t.Deleted = 'N'
AND prop_t.Deleted = 'N'

LEFT JOIN activity_t
ON Buy_Sell = 'S'
AND Ref_No = sell_t.Sellers_ID

GROUP BY prop_t.Agents_Prop_Code
;
However I have a problem in that if a seller has not had a property referenced to them they dont appear on the list.

I think its down to the part that does

....
INNER JOIN prop_t
ON sell_t.Sellers_ID = prop_t.Sellers_ID
....
But cant find a way forward.

Latest 3 Entries From My "friends" Query
I have a hypothetical query i'm struggling with:

table1: users
table2: user_posts
table3: friends_association_table

1) i have a list of id's that are my "friends" that i get by querying the friends_association_table

2) i need to get the latest 3 entries from each of these friends for a total of 15 or fewer (if i only have 1 friend with 1 entry for instance) entries

ignore the fiends aspect for a moment and consider only a query that asks

"what are the latest 3 post entries for each of these specific users (my friends) up to a total of 15 entries"

Query That Discloses "Locks" On Tables
I wrote a query for a popular non-MySQL database engine that displays WHO is locking WHICH table .....

How To Query ColumnA Or ColumnB="content"?
I need to do a query like the following for my ladder script. Essentially, I'm checking to see if there is already a row in the games table that was written today that involves the same people as the row they're currently trying to insert. If I get a positive result from the query on mysql_num_rows, I'll end the script with an error stating one must only post one match per opponent per day.

$query2="SELECT winner, loser, date from ladder_games where date>$yesterday and winner=($winnerid or $memnum) and loser=($winnerid or $memnum)";

So, I want it to match true if winner=$winnerid and loser=$memnum OR if winner=$memnum and loser=$winnerid.

&quot;update If Not Exit Insert&quot; Query?
is it possible to do query "update record. if not exist, do insert" in mysql?

Add COUNT(*) To Already Existing Query (was "How To Do This")
I have this query:
PHP

SELECT entries.*, categories.*, uploads.*, entries.blog_id FROM entriesINNER JOIN categories ON (categories.category_id = entries.category_id) LEFT JOIN uploads ON(uploads.blog_id = entries.blog_id) LEFT JOIN images ON (images.blog_id = entries.blog_id) ORDER BY entries.date_submitted DESC LIMIT 3

Now i want to add this
PHP

SELECT COUNT(*) FROM comments


but i dont know how to add it into the already existing query. The messages table has a column blog_id column in it so i could do a join like thisd LEFT JOIN comments ON
PHP

(comments.blog_id = entries.blog_id)

but i dont know how to get the first bit in there



Select Where Four Of The Ten Fields Are Same (was "query")
I have a table with ten fields. Now I want to select * from table where four of the ten fields are same. How can I do the query?

One Query, Three Outputs (was "Hello Guys")
i have my jsp form named frmAdminSelectid.jsp.
In this,i am coding to get data from database from one table called artist.
i have three different conditions where i need to display artistid's in three ways:

1> all those artist who have statusartist ='New' and flag1='on'
2> all those artist who have statusartist ='NewParked' and flag2='on'
3> all those artist who have statusartist ='NewParkedUpdt' and flag3='on'

i have coded 3 sets of queries and when i run them individually they run,but if i include them in my application one after the other,my tomcat application is closed and 'java.exe has encountered a problem' pop up window appears.

Following are my 3 sets of queries:

1> select a.artistid from artist as a,journalist as j where j.journid=7 and a.statusartist='New' and a.flag1='on' and a.artistid=j.journid;

2> select a.artistid from artist as a,journalist as j where j.journid=7 and a.statusartist='NewParked' and a.flag2='on' and a.artistid=j.journid;

3> select a.artistid from artist as a,journalist as j where j.journid=7 and a.statusartist='NewParkedUpdt' and a.flag3='on' and a.artistid=j.journid;

How To Do A "there Were X Results, This Is First Y" Result In 1 Query?
Let's say I have a database of book entries and I want to only retrieve the first 50 that have a certain author, even though there are more than 200 of them. What I'd like to output is a message saying, "Your search found 2xx results. Here are the first 50"

Is there a way to do this in one mysql query? I know how to do  it in two queries, a SELECT...LIMIT 50, and a COUNT query.

&quot;Recursive&quot; Query Issue
I'm having problems creating a query. The table I want to query has three columns - unique ID (auto_increment), parent row ID and a data row.

I want MySQL to return all the rows which have ID x (defined in the query), and check its parent ID and return the row with the same ID than the previous row had as parent ID. And this should continue until parent is 0, when it would stop.

Is this possible in MySQL (I'm using MySQL 5) and how can it be done? I have tested using variables with no success.


Copyright © 2005-08 www.BigResource.com, All rights reserved