How To Create Efficient MySQL Query From A Pseudo Query
I'm trying to build a webapplication where users can search for a person having a particular preference for color and material. To store this information I use the following structure (a MySQL dump can be found at the end of this post):
*table person with fields:
-persid: autoincrement id
-name: name of the person
*table material with fields:
-materialid: autoincrement id
-material: name of the material eg "wood"
*table color with fields:
-colorid: autoincrement id
-color: name of the color eg "green"
*table persmaterial with fields:
-persmatid: autoincrement id
-persid: link to table person
-materialid: link to table material
*table perscolor with fields:
-perscolorid: autoincrement id
-persid: link to table person
-colorid: link to table color
In the webapplication the search can be entered by the users as a kind of pseudo query:
(color=red OR color=blue) AND color=green AND material=iron
My question is: how can I automatically transform this pseudo query into an efficient MySQL query?
I have tried out some different options:
Option 1:
(SELECT p.persid FROM person p, perscolor pc, persmaterial pm WHERE p.persid=pc.persid AND (pc.colorid=1 OR pc.colorid=2) AND p.persid=pm.persid AND pm.materialid=2 GROUP BY p.persid HAVING (count(DISTINCT pc.colorid)=2 AND count(DISTINCT pm.materialid)=1)) UNION
(SELECT p.persid FROM person p, perscolor pc, persmaterial pm WHERE p.persid=pc.persid AND (pc.colorid=2 OR pc.colorid=3) AND p.persid=pm.persid AND pm.materialid=2 GROUP BY p.persid HAVING (count(DISTINCT pc.colorid)=2 AND count(DISTINCT pm.materialid)=1))
Remarks:
*I do not see how to turn a general pseudo query into a query like the one in option 1, except for turning the pseudo query into a sum of products form where the sulms would correspond to the UNIONs. IS there a clever way to obtain such a sum of products form from an arbitrary pseudo query?
Option 2:
SELECT persid FROM person p WHERE
(EXISTS(SELECT * FROM perscolor pc WHERE pc.colorid=1 AND p.persid=pc.persid)
OR
EXISTS(SELECT * FROM perscolor pc WHERE pc.colorid=3 AND p.persid=pc.persid))
AND
EXISTS(SELECT * FROM perscolor pc WHERE pc.colorid=2 AND p.persid=pc.persid)
AND
EXISTS(SELECT * FROM persmaterial pm WHERE pm.materialid=2 AND p.persid=pm.persid)
Remarks:
*very easy to get from pseudo query to MySQL query but what about performance?
Option 3:
SELECT p.persid FROM person p, perscolor pc, persmaterial pm WHERE
p.persid=pc.persid
AND
(pc.colorid=1 OR pc.colorid=2 OR pc.colorid=3)
AND p.persid=pm.persid
AND pm.materialid=2
GROUP BY p.persid HAVING
sum(case when pc.colorid in (Ƈ',Ɖ') then 1 else 0 end) >= 1
AND
sum(case when pc.colorid=ƈ' then 1 else 0 end)>=1
AND
sum(case when pm.materialid=ƈ' then 1 else 0 end)>=1
Remarks:
*this option requires the pseudo query to be turned into a product of sums form; again is their a clever way to obtain such a form;
Option 4
SELECT DISTINCT pc1.persid FROM perscolor pc1
INNER JOIN perscolor pc2
ON pc1.persid=pc2.persid AND pc2.colorid=2
INNER JOIN persmaterial pm1
ON pc1.persid=pm1.persid AND pm1.materialid=2
LEFT OUTER JOIN perscolor pc3
ON pc1.persid=pc3.persid AND pc3.colorid=1
LEFT OUTER JOIN perscolor pc4
ON pc1.persid=pc4.persid AND pc4.colorid=3
WHERE COALESCE(pc3.persid,pc4.persid) IS NOT NULL
Remarks:
*this option requires the pseudo query to be turned into a product of sums form
Option 5:
SELECT p.persid FROM person p, persmaterial pm,perscolor pc1,perscolor pc2,perscolor pc3 WHERE p.persid=pm.persid AND p.persid=pc1.persid AND p.persid=pc2.persid AND p.persid=pc3.persid AND (pc1.colorid=1 OR pc2.colorid=3) AND pc3.colorid=2 AND pm.materialid=2 GROUP BY p.persid
Remarks:
*very easy to get from pseudo query to MySQL query but what about performance?
-- phpMyAdmin SQL Dump
-- version 2.6.1
-- http://www.phpmyadmin.net
--
-- Host: localhost
-- Generation Time: Oct 19, 2006 at 01:13 PM
-- Server version: 4.1.9
-- PHP Version: 4.3.10
--
-- Database: `aston`
--
-- --------------------------------------------------------
--
-- Table structure for table `color`
--
CREATE TABLE `color` (
`colorid` int(11) NOT NULL auto_increment,
`color` varchar(30) NOT NULL default '',
PRIMARY KEY (`colorid`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=5 ;
--
-- Dumping data for table `color`
--
INSERT INTO `color` VALUES (1, 'red');
INSERT INTO `color` VALUES (2, 'green');
INSERT INTO `color` VALUES (3, 'blue');
INSERT INTO `color` VALUES (4, 'yellow');
-- --------------------------------------------------------
--
-- Table structure for table `material`
--
CREATE TABLE `material` (
`materialid` int(11) NOT NULL auto_increment,
`material` varchar(30) NOT NULL default '',
PRIMARY KEY (`materialid`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;
--
-- Dumping data for table `material`
--
INSERT INTO `material` VALUES (1, 'wood');
INSERT INTO `material` VALUES (2, 'iron');
-- --------------------------------------------------------
--
-- Table structure for table `perscolor`
--
CREATE TABLE `perscolor` (
`perscolorid` int(11) NOT NULL auto_increment,
`persid` int(11) NOT NULL default Ɔ',
`colorid` int(11) NOT NULL default Ɔ',
PRIMARY KEY (`perscolorid`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=7 ;
--
-- Dumping data for table `perscolor`
--
INSERT INTO `perscolor` VALUES (1, 1, 1);
INSERT INTO `perscolor` VALUES (2, 1, 2);
INSERT INTO `perscolor` VALUES (3, 2, 1);
INSERT INTO `perscolor` VALUES (5, 3, 3);
INSERT INTO `perscolor` VALUES (6, 3, 2);
-- --------------------------------------------------------
--
-- Table structure for table `persmaterial`
--
CREATE TABLE `persmaterial` (
`persmatid` int(11) NOT NULL auto_increment,
`persid` int(11) NOT NULL default Ɔ',
`materialid` int(11) NOT NULL default Ɔ',
PRIMARY KEY (`persmatid`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=6 ;
--
-- Dumping data for table `persmaterial`
--
INSERT INTO `persmaterial` VALUES (1, 1, 1);
INSERT INTO `persmaterial` VALUES (2, 1, 2);
INSERT INTO `persmaterial` VALUES (3, 2, 1);
INSERT INTO `persmaterial` VALUES (5, 3, 2);
-- --------------------------------------------------------
--
-- Table structure for table `person`
--
CREATE TABLE `person` (
`persid` int(11) NOT NULL auto_increment,
`name` varchar(30) NOT NULL default '',
PRIMARY KEY (`persid`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=4 ;
--
-- Dumping data for table `person`
--
INSERT INTO `person` VALUES (1, 'john');
INSERT INTO `person` VALUES (2, 'emily');
INSERT INTO `person` VALUES (3, 'liz');
View Complete Forum Thread with Replies
Related Forum Messages:
Slow Query->Efficient Query
I have a query that is running really slow !!!! I have joined on Key fields and indexed the tables fully but it is still solw. -------------------------------------------- select d.id, a.signed, u.Forename, u.Surname, d.paid, p.date, d.payment, p.amount, d.acctual from details d join poten a on a.id = d.id left join recieved p on d.id = p.id left join users u on a.signed = u.userid where d.paid > '01-Dec-2005' and d.authorrceived is not null and d.authorrefused is null and ((d.payment starting 'E' or d.payment starting 'e') or (d.payment starting 'Q' or d.payment starting 'q' and p.target = '500')) order by d.paid, a.signed, d.id
View Replies !
CREATE TABLE And MySQL Query Browser
I am using the ODBC 3.51 Driver to Do a "create database" and then create some tables on that database. I see in the ..mysqldata directory my new database I have created and the associated .frm files, however MySQL Query Browser and Administrator do not see these schema's. I am guessing it may be due to user privileges. MySQL is running locally and the connection string does not contain a Username and password. Also, when I do show databases from within the Query Browser, it does not show my Database, only the one that I had created manually. There must be some more setup that I am not aware of to register the Database or something.
View Replies !
Create MySQL Select Query From The A Field Using SUBTRING_INDEX
Is it possible to create a MySQL query to do the following. Extract from TABLE.field, which is defined as text, containing either NULL, number (e.g. 54) or range of numbers (e.g. 70-95). Then use the extracted number within a WHERE clause I have looked into using something like SELECT SUBSTRING_INDEX(table.field, '-', 1); Problem is I don't know how to use this within the WHERE clause.
View Replies !
Lost Connection To MySQL Server During Query (create Database)
I downloaded the MySQL trail version a few month ago, it worked fine. however after i brought 1 x EMS MySQL Manager Professional (Non-commercial license) and registered but the tool doesn't work anymore... when i try to register a database and try to get it connect, it through me a error message "Lost connection to MySQL server during query". more to it... when i try to create a database at my local host, a error messate says "can't connect to MySQL server on localhost (10061)... PLease help!
View Replies !
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.
View Replies !
How To Create This Query?
I am having trouble creating this. I have a table of categories. A category is either a regular category named or it is a sub-category and the parent category is linked by 'category_id'. These are all in one table, I did not create a seperate table for sub categories. How would I do this? Select from the database `categories` grouping them by first the main category and then all the other categories under it by 'parent_id'? This is my current query but it is not working: SELECT * FROM categories GROUP BY category_id, parent_id
View Replies !
Create General Query Log
I am trying to turn on General logging on mysql server [on a RHE linux box]. If I go >mysqld -l filename on shell, it says "command not found". What is the best way to create General log on a live server. Somehow MYSQL server doesn't have a my.cnf file. I have searched all over but there are no signs. Whenever I have to start/stop/restart the server, I use the ready-made mysql script.
View Replies !
Create Table Query
I just dump this script from another database so I could add the same create table query for different db, when I run the query I get the error. mysql> CREATE TABLE SENT_MESSAGES ( -> INDNUMBER int(11) NOT NULL auto_increment, -> CLIENT varchar(100) NOT NULL default '', -> CODE varchar(100) NOT NULL default '', -> TYPE varchar(100) NOT NULL default '', -> WHEN timestamp(14) NOT NULL, -> PRIMARY KEY (INDNUMBER) -> ) TYPE=MyISAM; ERROR 1064: You have an error in your SQL syntax near 'WHEN timestamp(14) NOT NULL, PRIMARY KEY (INDNUMBER) ) TYPE=MyISAM' at line 6
View Replies !
Create A Query Starting From A Value
I would like to know how to create a query which will return a certain number of rows from a database, starting from a particular key value. Something like SELECT * FROM users STARTING FROM id=7 ORDER BY name LIMIT 5 Does something that does this exist? I can't use WHERE id>7 because I am sorting on a different field and so the id field is unsorted.
View Replies !
Create An Array From Sql Query
I need help with a mysql query, I am adding some java code to a page which requires a list in array format: array("value1", "value2", "etc") I need to be able to return the results from a sql query and convert them into an array. The query looks something like: SELECT value1, value2 from some_table ORDER BY value1 ASC" I only need one of the values returned from the query in the array.
View Replies !
How To Create A Query To Get Top 5 Item For Each Date
I have running out of idea on hw to create a query to get each day top 5 item with a date range given more than 1 month or more. meant: if i have a date range from 2006-01-23 to 2006-10-23, then i want to get the latest 31 days data only with each day TOP 5 item. How? Lets say i have a table with this keyword: MyDate;Item;CountItem; The date range is unknown and can be any range selected by user. I am trying to think of put auto increament for each day with CountItem desc and each day the column of auto-increament is set to 5 only so at last i can just get all the data from it. But the question is i dunno how to do it? Anyone have better solution? I know if using store procedure then can do this but is it can done without store prodedure?
View Replies !
Create Table With Result Of A Query?
Is there a way to create a table with the results of a query? i.e. I want to create a table of the with the users who registered on my site on January, Feb and so on ... All this records are stored in a single table: users, and there is a field called date_join, so i want to create a table with only the users who registered on january and name it users_jan for example ..
View Replies !
Create A Query To Insert Data
I have a form that includes a bunch of fields to fill out. I have the query working for most of them, but right now am stuck on getting one area to work. I have 7 fields where you can input a parts number (name=number[]) and then another 7 fields where you input the description of the part (name=description[]). I want to put them into a database that has one column for the number, one column for the description and then a primary key and foreign key to eventually join them to the main workorder table. I am not sure how to make a query that will INSERT them into the DB columns, one row for each number/description combination, and check to make sure there is data in the rows. There may not always be 7 part number/descriptions in the form fields and I don't want a bunch of empty rows in the DB table.
View Replies !
USE After DROP And CREATE (script In Query Browser)
I'm writing a simple script that creates the database and tables: ------------------------------------ DROP DATABASE IF EXISTS mydb; CREATE DATABASE mydb CHARACTER SET utf8 COLLATE utf8_unicode_ci; /*workaround: use mysql; */ use mydb; DROP TABLE IF EXISTS movie; CREATE TABLE movie ( id int not null auto_increment primary key ); ------------------------------------ When executing, Query Browser says "No database selected (1046)" on lines with table names. I add USE <dbname> after its creation, but it only works if the previous default database is different. A work-around is to add "USE mysql" just before the real USE, but it's ugly. Any solutions?
View Replies !
Create URL From To Database Fields In Query Results
I have a MySQL database with table that works as document library. Table keeps details about docs on our server. There are bunch of fields but the key ones here are FileName, URL and location. I'm using PHP to work with the MySQL Database hosted on a Mac OS X Server. Basically, I have a query set up to pull certain records based on a field called Keywords. On the result page I want a field (or item) that combines the URL field and Filename field that ultimately points to the phycial location of the file. For every record thr url field contents is the same since the physical location of the files are in the same directory on the server. Right now the URL field has http://www.mysite.com/docs/. I'd like the result page to have the filename shown, but that filename would be a link to URL+filename. Is there a way to do this? .....
View Replies !
How To Create Complex Query With Group By And Count
I have a table usertags: usertags ------------ - usertagid - usertagsiteid - usertagtext I want to select the usertagtext and count of usertagtext grouped by usertagtext. I only want it to show usertagtext that also have a match in the usertagsiteid to a given value for usertagtext. Not sure if that makes sense so here is an example: ......
View Replies !
Getting Count(*) When Using Pseudo Pivot Tables...
In the usual case, this SQL select count(*) from mytable where ... returns an accurate count of the rows you want. But how do I go about counting rows from this SQL (the sum...if statements function as a pseudo pivot query)? SELECT sum(IF(date_report = ('2005-06-30'),shares,0)) as 'Q2 2005',sum(IF(date_report = '2005-03-31',shares,0)) as 'Q1 2005' from companies left join positions on co_id = positions_co_id where positions_co_issue_id = 7194 AND date_report in('2005-06-30','2005-03-31') group by co_id order by 'Q2 2005' DESC In this case, I'll end up with a row count of, say, 360. When I try to count the rows I come up with numbers way different. For instance, this try: select count(co_id) from companies left join positions on co_id = positions_co_id where positions_co_issue_id = 7194 AND date_report in('2005-06-30','2005-03-31') ....might give me 1000, while this one... select count( distinct co_id) from companies left join positions on co_id = positions_co_id where positions_co_issue_id = 7194 AND date_report in('2005-06-30','2005-03-31') ....might give me 320.
View Replies !
Simple Sql Question: Using A Query Result As A Query Variable
EDIT: it works now, I had an error in my code, not my method. I have a very simple question. I have 2 tables: 'users' and 'posts' with the following structure: users: id, username, email_address posts: id, user_id, post_title, post_text in a my own mind's mysql, I would like to: SELECT posts.id, posts.user_id, posts.post_title, posts.post_text users.username FROM users, posts WHERE posts.user_id = users.id I usually do one query for the post data, and then, based on the use_id record, do another of the users table, but today, I'm being forced to do them in one swoop.
View Replies !
Is This An Efficient MySQL Setup?
I would like to offload the MySQL server from my dedicated box in order to speed up page loads. I don't have an additional dedicated server so my only option is to get a VPS. But is offloading the MySQL server to a VPS, albeit a modest one, even worthwhile? I understand this is a very broad question because I am not providing any details but that being the case I am expecting a broad answer
View Replies !
Most Efficient, Stable Version Of MYSQL?
We're still using mysql 3.23.56, so it's time to upgrade! It has never once crashed on us, so we've been content with it so far. However, some of the inefficient query optimizations make us want to upgrade. Does anyone know what the current most efficient and stable version of MYSQL is? We don't require views or cursors or stored procedures or any of that... Just whatever's the most reliable and best optimized for fast query execution of fairly simple SQL. I know that 3.23 has some issues with using indices correctly during optimization (most notably in ORDER BY ... DESC). Is that problem fixed in 4?
View Replies !
Reusing A Query Output In The Same Query
I am guessing a basic question but not one I can find an obvious answer to. If I create a calculated or modified column in a query (such as a modified text string), and then want to reuse that in the same query as I need to do three or four operations on it in sequence, how do I do it in mySQL 4.1? Do I need to create a new column to store the interim result in an existing table (and then clear or alter it each time I run the query), or create a temporary table, or is there an easy way to reuse the query output in the same query (does the query have a name like a table name)? If it requires a new column or table, are there particular disciplines to ensure it is robust and self maintaining?
View Replies !
Pagination W/1 Query + How To Use Query With Indexes
i'm asking 2 questions in 1 thread because i don't wanna take up too much room, hopefully no one will mind. i have mysql 4.1.10 1) i want to find all the rows that were edited this month. the query i currently have ( MONTH(CURDATE()) = MONTH(date) ) doesn't use indexes. how can i manipulate it so i can take advantage of indexes. 2) this is something i've always wondered, but usually just assumed was not possible. if i am listing some results, say 20 per page, how can i get both the total number of results as well as the 20 items required for that specific page. say there are 2 million total results, so grabbing them all and showing just 20 is not an option. if this is not possible what is the most efficient way of making both queries?
View Replies !
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
View Replies !
Query Across DBs In MySQL
I'm new to MySQL and am wanting to be connected to the MySQL server and query across diffrent db's. To my understanding a different db in MySQL is the same as a schema in Oracle. Am I correct in this thinking? What I want is to have one DB called projects which has common tables such as contact_details, postal_codes, language and so on. Then a number of other db's for different projects. Then project1 has its own tables but can also see those in the projects db.
View Replies !
MySQL Query
I have a table called "sales"with two fields that I want to use for a calculation and then sum in a MySQL Query. One field is "price", the other is "exchange_rate". I want the sum of all "price/exchange_rate" in the table. I have the following: PHP Code: SELECT SUM(sales.price/sales.exchange_rate) AS total FROM sales WHERE .... What am I doing wrong?
View Replies !
MySQL Query Log
I have huge load on my site because of mysql database queries. I did necessary indexes and make some optimisations on data values. Now I'm tryin "EXPLAIN SELECT" query to find slow queries. But if I get a query log with query times that will be a shortcut to find the problem. Has mysql got a query log and where can I find it? Do you recommend a tool or script to log mysql queries? If I can see on the server that would be so helpful. But I can try on my windows localhost too.
View Replies !
Mysql Query.
i have a small staff auction for work. here is the query: SELECT * FROM listing l, bids b, users u WHERE l.listingid=b.listingidAND u.username=b.buyer AND biddate = (SELECT MAX(biddate) FROM bids bi WHERE bi.listingid= b.listingid)AND l.enddate < NOW() + INTERVAL 8 HOUR this is good but some auctions may have many winners in buy now format. so therefore, because of the SELECT MAX(biddate) part, this is just bringing the last bidder (winner) in all auctions. however, its also selecting only one buynow who is the winner too but there are other winners in buynow. in this case, i added this to the query: OR b.format='buynow' Because i want it to select all the buynows as all buynows are winners but then only select the maxdate only for those in the bid format auctions.
View Replies !
Mysql 5.0 Query
im new to mysql and trying to get to grips with it.I am a complete begineer with this.I have installed it how it said in the manual and everything. The question i want to know is how do you program mysql.I have the command line client and i found a tutorial to add new user with this but is this where you do all mysql or do you key it in notepad or like? If you do key it in command line client can you save the files.
View Replies !
Mysql Query Log
I have used mysql 5.0 alpha and php to build a shop cart system.I installed all of those in windows. Coz I would like to set up a common query log, so i use "mysqld --log=fileName" to generate a log file。The result is the log file has been successfully generated, but there is nothing inside . For exampe, I run "mysqld --log=test.log" (test.log is the log name given by myself). In the data folder, there is an file called "test.log" has been generated. There is not any log information inside except those general information. Even I have done some searching SQL command not only in the shop cart system, but also in the MySQL command prompt, it seems like mysql never write anything into that log file. I don't know what is going on here or is there something I should do but I didn't do or something else. Please help me. The following are the contents in my log file. That's all of them, no matter how long I wait. -----------------------------------------------------------test.log mysqld, Version: 5.0.0-alpha-max-debug-log, started with: Tcp port: 3306 Unix socket: MySQL Time Id Command Argument
View Replies !
Fed Up With MySql, Can Someone Help Me Run This ****ing Query?
I come from MS SQL 2005 background and I cannot get this MySql query to run.. INSERT INTO [lookup] ([Type],[Key],[Value],Rank,Status,Created) VALUES (1,2,'a',1,1,CURRENT_DATE()); Why won't this run??? (I know type, key, value are MySql "keywords" BUT I use the column definitions []). In MS SQL 2005, this works fine perfectly. Also, how the ***** do I run multiple sql statements in MySql query browser? Which ****** developer wrote it so you can only run one statement at a time? It's these little annoying ****** that make me switch back to MS SQL. Also, how the ***** do you declare variables in MySQL WITHOUT using a ***** stored procedure? Here's what I want to run IN MS SQL 2005: DECLARE @Id INT; SET @ID = 0; DECLARE @ResultDate Date; SET @ResultDate = GETDATE(); Begin IF @ID > 0 BEGIN INSERT INTO User (Name, Created) VALUES ('test', @ResultDate); SELECT @ID = @@IDENTITY; END ELSE BEGIN UPDATE User SET Name = @Name, Modified = @ResultDate WHERE ID = @ID; END SELECT @ID as ID, @ResultDate as ResultDate Try and Convert that into MS SQL (INLINE SQL...not a function, not a procedure, INLINE SQL). Is this possible in MySql? If it isn't, I'm done with open source crapola. People keep talking how Microsoft sucks, but at the end of the day...Microsoft actually has products that get the job done.
View Replies !
Can Anyone Help With This Mysql Query?
I'm using the following query to join the 3 tables gallery_category, gallery_photos and spectacle: PHP SELECT gallery_category.id AS gcid, gallery_category.name AS gcname, private, COUNT(photo_id) AS countim, spectacle.id AS sid, spectacle.name AS showname FROM gallery_category LEFT JOIN gallery_photos ON gallery_category.id=gallery_photos.photo_category LEFT JOIN spectacle ON gallery_category.spectacle=spectacle.id GROUP BY gallery_photos.photo_category ORDER BY gallery_category.name ASC It seems to work fine, but it will only return 3 rows. If I add a new entry to the gallery_category table, the result from the query doesn't return it. If I then add an entry to the gallery_photos table with the new gallery_category in the column gallery_photos.photo_category (i.e. I add a photo to the new category), then the new category will be returned in my result set. My first thought was that it was ignoring categories with no photos in, but this is not the case (one of the 3 rows returned has no photos - countim=0).
View Replies !
MySQL Query Help Please...
How do i select full names from a table which start from any number ? I am having a table named users in which i am simply retriving records by alphabets for eg. All names starting with A or B or C...i am getting this done by using the following: sql = "SELECT * FROM users WHERE fullname = 'A%'"; But i don't know how to retrieve all records which start from 1,2,3,4,5,6,7,8,9,0 all at once. I will all records to be retrieved at once which start from a number or who's first char. is a number.
View Replies !
MySQL Query, Is It Possible?
I have the following table-structure: countID countItemCode countIPaddress countWhat (in or outclick) countReferer Is it possible to make a mySQL query that outputs the following #38AFG66 total clicks: 34 (in:12,out:20) referrer (site1:10,site2:12,site3:2) #JHGS676 total clicks: 45 (in:31,out:14) referrer (site1:8,site2:7,site3:5,site4:25)
View Replies !
Help With Php/MySQL Query?
I'm trying to pull records from a MySQL database using a sql query - to pull records where the "exp_date" field is greater than or equal to today. How do I do this? Here is my query: PHP $query = "SELECT v_title,link_id,v_descr,hw_added,hw_region_id,approved,user_approved,exp_date FROM ec3_ad WHERE hw_feat=1 AND approved=1 AND user_approved=1 AND hw_region_id=103 AND exp_date>=strftime('%d %b %Y %H:%M:%S') ORDER BY hw_added DESC LIMIT 20"; ... but this is obviously not working because I don't know how to add today's date/time dynamically to the query.
View Replies !
|