in my forum i have threads and replies.
one thread has multiple replies. but then, a reply can be a reply of an reply (like google wave). because of that a reply has to have a column "reply_id" so it can point to the parent reply. but then, the "top-level" replies (the replies directly under the thread) will have no parent reply.
so how can i fix this? how should the columns be in the reply table (and thread table).
at the moment it looks like this:
threads:
id
title
body
replies:
id
thread_id (all replies will belong to a thread)
reply_id (here lies the problem. the top-level replies wont have a parent reply)
body
what could a smart design look like to enable reply a reply?
I want to insert into multiple tables in same query by using BEGIN and COMMIT.
It seems the error occur at begin.
here is my SQL command
BEGIN
INSERT INTO Product (pName, pBrand, pCategory, pSize, pQuantity, pPrice, pDetail)
VALUES('$name', '$brand', '$category', '$size', '$quantity', '$price', '$detail')
INSERT INTO Image (iName, iExt, iSize, pID)
VALUES('$img_name', '$img_ext', '$img_size', LAST_INSERT_ID());
COMMIT;
I am trying to output data from
table : artists
row : artist
into this format.
Artist Names can have special characters and there are over 16k of them.
It needs to be written to a file. called anything artist.php for example
$Artist = array(
"Name from database",
"Name from database",
"Name from database",
"Name from database",
"Name from database"
);
ok sorry for not explaining. do this for ajax auto complete.. so i need to create a file with this array in it.
here is the exact script
http://www.brandspankingnew.net/specials/ajax_autosuggest/ajax_autosuggest_autocomplete.html
I have following table :
id dateStart dateEnd active
1 2012-11-12 2012-12-31 0
2 2012-11-12 2012-12-31 0
I want to compare todays date in between dateStart and dateEnd.
Following is my query for this :
$todaysDate="2012-26-11";
$db = Zend_Registry::get("db");
$result = $db->fetchAll("SELECT * FROM `table` WHERE active=0 AND {$todaysDate} between dateStart and dateEnd");
return $result;
But its not working.
Any solution.
Thanks in advance.
How do I drop selected tables in Rails? I want to drop all tables from a database with a given prefix. PHPMyAdmin would be very useful at this point.
Thanks
SELECT categories.*, COUNT(categoryID) AS kritCount
FROM categories AS categories
LEFT JOIN krits ON categories.id = categoryID
WHERE (krits.approved = '1')
GROUP BY categories.id
So this works great except that it does not return a category that has a 0 count of krits in the category.
It will if I remove the WHERE statement but I need the WHERE to only select the krits where the field approved = 1
"SELECT id as Id from dbTable WHERE code = ? AND CURDATE() BETWEEN
start_date AND end_date AND offerId IN ('12321', '12124')";
//Passing arguments for the query
$args = array_merge(array(51342),$offerid);
//Execute the prepared query
$statement->execute($args);
Now array(51342) represents combination of code+value, aside my database has value, code columns
and so I want a query which would look logically like
"SELECT id as Id from dbTable WHERE code and value
(Note here I do not know the syntax, what am looking at is (code+value = ?), please advise on query) = ?
AND CURDATE() BETWEEN start_date AND end_date AND offerId IN ('12321', '12124')";
I'm attempting to run a query that adds up the total number of subjects in a class. A class has many subjects. There is a 'teachersclasses' table between teachers (the user table) and classes. The principles sounds pretty simple but I'm having some trouble in getting my page to display the number of subjects for each class (directly associated with the teacher)
This is what I have so far, trying to make use of the COUNT with a nested SELECT:
SELECT (SELECT count(*) FROM subjects WHERE subjects.classid = class.classid) AS total_subjects, class.classname, class.classid
FROM class
Then I am calling up 'num_subjects' to present the total within a while loop:
<?php echo $row['total_subjects']?>
From the above, I am receiving the total subjects for a class, but within the same table row (for one class) and my other while loop doesnt run anymore, which returns all of the classes associated with a teacher :( ... Bit of a mess now!
I know to return the classes for a particular teacher, I can do an additional WHERE clause on the session of 'teacherid' but I think my query is getting too complicated for me that errors are popping up everywhere. Anyone have a quick fix for this! Thanks very much
I have a problem in the code.i have two tables 'sms' and 'bd_paid_bribe'.sms table has a column 'Message' and bd_paid_bribe table has a column 'c_addi_info'.when i execute the code first time all the values of Message column are inserted into c_addi_info column.when i enter a record for the second time instead of inserting the new record, all the records of Message column are inserted into bd_paid_bribe column.can u modify the code and provide a solution to avoid duplication and to insert only the newly added record.
<?php
$con=mysql_connect('localhost','root','');
if(!$con)
{
die("couldn't connect");
}
mysql_select_db("ipab2",$con);
$rs2=mysql_query(" select max(sms_index) from tab3");
do
{
$rs=mysql_query("insert into tab3(sms_index)select max(sms_index) from sms");
$rs3=mysql_query("SELECT max(sms_index) FROM sms");
$rs1=mysql_query("insert into bd_paid_bribe(c_addi_info) select
Message from sms ");
}while($rs2>$rs3);
?>
I've use following code
$con = mysql_connect("localhost","root","");if (!$con) {die('Could not connect: ' . mysql_error());}
It's works. but when
$db_host='localhost';$db_id='root';$db_pass='';
$con = mysql_connect($db_host,$db_id,$db_pass);if (!$con) {die('Could not connect: ' . mysql_error());}
it didn't works, trying to swap ("),('),and empty in mysql_connect() and in $var and vice versa. Any help would be appreciated. Thanks.
Hello,
I am trying to use this query to return every instance where the variable $d['userID'] is equal to the User ID in a separate table, and then echo the username tied to that user ID.
Here's what I have so far:
$uid = $d['userID'];
$result = mysql_query("SELECT u.username
FROM users u
LEFT JOIN comments c
ON c.userID = u.id
WHERE u.id = $uid;")$row = mysql_fetch_assoc($result);
echo $row['username'];
I have two tables in my database, one contains a list of items with other information on these items. The other table is contains a list of photographs of these items.
The items table gives each item a unique identifier,which is used in the photographs table to identifier which item has been photographed.
I need to output a list of items that are not linked to a photograph in the second table. Any ideas on how I can do this?
This is for an upcoming project. I have two tables - first one keeps tracks of photos, and the second one keeps track of the photo's rank
Photos:
+-------+-----------+------------------+
| id | photo | current_rank |
+-------+-----------+------------------+
| 1 | apple | 5 |
| 2 | orange | 9 |
+-------+-----------+------------------+
The photo rank keeps changing on a regular basis and this is the table that tracks it:
Ranks:
+-------+-----------+----------+-------------+
| id | photo_id | ranks | timestamp |
+-------+-----------+----------+-------------+
| 1 | 1 | 8 | * |
| 2 | 2 | 2 | * |
| 3 | 1 | 3 | * |
| 4 | 1 | 7 | * |
| 5 | 1 | 5 | * |
| 6 | 2 | 9 | * |
+-------+-----------+----------+-------------+ * = current timestamp
Every rank is tracked for reporting/analysis purpose.
I talked to someone who has experience in this field and he told me that storing ranks like above is the way to go. But I'm not so sure yet.
The problem here is data redundancy. There are going to be tens of thousands of photos. The photo rank changes on a hourly basis (many time within minutes) for recent photos but less frequently for older photos. At this rate the table will have millions of records within months. And since I do not have experience in working with large databases, this makes me a little nervous.
I thought of this:
Ranks:
+-------+-----------+--------------------+
| id | photo_id | ranks |
+-------+-----------+--------------------+
| 1 | 1 | 8:*,3:*,7:*,5:* |
| 2 | 2 | 2:*,9:* |
+-------+-----------+--------------------+ * = current timestamp
That means some extra code in PHP to split the rank/time (and sorting) but that looks OK to me.
Is this a correct way to optimize the table for performance? What would you recommend?
Any suggestions would be great.
I need a query to return this result:
+---------+-----+-------+
| ref_nid | nid | delta |
+---------+-----+-------+
| AA | 97 | 1 |
| BB | 97 | 2 |
| CC | 97 | 3 |
| DD | 98 | 1 |
| EE | 98 | 2 |
| FF | 98 | 3 |
+---------+-----+-------+
However, I do not have the delta column. I need to generate it for each nid group.
In other words, I need an auto incremented number for each group of the result.
I have been looking for a while now but I can not find an easy solution for my problem. I would like to duplicate a record in a table, but of course, the unique primary key needs to be updated.
I have this query:
INSERT INTO invoices
SELECT * FROM invoices AS iv WHERE iv.ID=XXXXX
ON DUPLICATE KEY UPDATE ID = (SELECT MAX(ID)+1 FROM invoices)
the problem is that this just changes the ID of the row instead of copying the row. Does anybody know how to fix this ?
Thank you verrry much,
Digits
//edit: I would like to do this without typing all the field names because the field names can change over time.
Hello.
I have problem with optimize this query:
SET @SEARCH = "dokumentalne";
SELECT SQL_NO_CACHE
`AA`.`version` AS `Version` ,
`AA`.`contents` AS `Contents` ,
`AA`.`idarticle` AS `AdressInSQL` ,
`AA` .`topic` AS `Topic` ,
MATCH (`AA`.`topic` , `AA`.`contents`) AGAINST (@SEARCH) AS `Relevance` ,
`IA`.`url` AS `URL`
FROM `xv_article` AS `AA`
INNER JOIN `xv_articleindex` AS `IA` ON ( `AA`.`idarticle` = `IA`.`adressinsql` )
INNER JOIN (
SELECT `idarticle` , MAX( `version` ) AS `version`
FROM `xv_article`
WHERE MATCH (`topic` , `contents`) AGAINST (@SEARCH)
GROUP BY `idarticle`
) AS `MG`
ON ( `AA`.`idarticle` = `MG`.`idarticle` )
WHERE `IA`.`accepted` = "yes"
AND `AA`.`version` = `MG`.`version`
ORDER BY `Relevance` DESC
LIMIT 0 , 30
Now, this query using ^ 20 seconds. How to optimize this?
EXPLAIN gives this:
1 PRIMARY AA ALL NULL NULL NULL NULL 11169 Using temporary; Using filesort
1 PRIMARY ALL NULL NULL NULL NULL 681 Using where
1 PRIMARY IA ALL accepted NULL NULL NULL 11967 Using where
2 DERIVED xv_article fulltext topic topic 0 1 Using where; Using temporary; Using filesort
This is example server with my data:
user: bordeux_4prog
password: 4prog
phpmyadmin: http://phpmyadmin.bordeux.net/
chive: http://chive.bordeux.net/
I'm creating a members site, and I'm currently working on the user Preference settings. Should I create a table with all the preference fields (about 17 fields) or should I include them in the main member table along with the account settings?
Is there a limit as to how many fields I should have in a table? currently the member table has about 21 fields... not sure if its okay to add another 17 more fields when I can easily just put them in another table. It'll take more coding to pull up the data though... any sugguestions?
I have my table columns set like this:
likes(id, like_message, timestamp)
id is the primary key that is auto incrementing. This is the SQL that I use to add a row:
$sql = "INSERT INTO `likes` (like_message, timestamp)
VALUES ('$likeMsg', $timeStamp)";
Everything works, but now I need to throw back the id attribute of the newly inserted row. For example, if I insert a row and the id of that row is 13, I need to echo out 13 so my AJAX request can pick that up and use it.
Any help would be appreciated, as well as related code samples. Thanks :)
I keep getting the same number outputted for the Total Sales, Minimum Sale, Largest Sale and Average Sale.
The Total Invoices is working perfectly, but I cant seem to figure out how to fix the other ones.
Here's the query:
SELECT SUM( b.`Number of Invoices`) AS `Total Invoices`,
SUM( b.`Total Customer Purchases`) AS `Total Sales`,
MIN( b.`Total Customer Purchases`) AS `Minimum Sale`,
MAX( b.`Total Customer Purchases`) AS `Largest Sale`,
AVG( b.`Total Customer Purchases`) AS `Average Sale`
FROM (SELECT a.CUS_CODE,
COUNT(a.`Number of Invoices`) AS `Number of Invoices`,
SUM(a.`Invoice Total`) AS `Total Customer Purchases`
FROM ( SELECT CUS_CODE,
LINE.INV_NUMBER AS `Number of Invoices`,
SUM(LINE.LINE_UNITS * LINE.LINE_PRICE) AS `Invoice Total`
FROM `ttriggs`.`INVOICE`, `ttriggs`.`LINE`
WHERE INVOICE.INV_NUMBER = LINE.INV_NUMBER
GROUP BY CUS_CODE, LINE.INV_NUMBER
) a
) b
GROUP BY b.CUS_CODE;
Heres the database diagram
https://www.dropbox.com/s/b8cy5l29jwh8lyv/1_edit.jpg
Subquery generates:
CUS_CODE 10011
Number of Invoices 8
Total Customer Purchases 1119.03
Any help is greatly appreciated,
Thanks!
I have a table which I want to record the timestamp of every order at every insertion time. However, I'm getting zero values for the timestamps.
Here's my schema:
CREATE TABLE IF NOT EXISTS orders(
order_no VARCHAR(16) NOT NULL,
volunteer_id VARCHAR(16) NOT NULL,
date TIMESTAMP DEFAULT NOW(),
PRIMARY KEY (order_no),
FOREIGN KEY (volunteer_id) REFERENCES volunteer(id)
ON UPDATE CASCADE ON DELETE CASCADE)
I'm trying to find 2 different result via JOINS.
Table look like;
SELECT id,member_id,registered_year FROM records;
I can listing which members registered in 2012 and also in 2013 with;
SELECT member_id FROM records a
INNER JOIN records b ON a.member_id=b.member_id
WHERE a.registered_year='2013' AND b.registered_year='2012';
But I can't list revers of It. How can I list which members were registered in 2012 but not in 2013?
Thnx in advance.
$activeQuery = mysql_query("SELECT count(`status`) AS `active` FROM `assignments` WHERE `user` = $user_id AND `status` = 0");
$active = mysql_fetch_assoc($activeQuery);
$failedQuery = mysql_query("SELECT count(`status`) AS `failed` FROM `assignments` WHERE `user` = $user_id AND `status` = 1");
$failed = mysql_fetch_assoc($failedQuery);
$completedQuery = mysql_query("SELECT count(`status`) AS `completed` FROM `assignments` WHERE `user` = $user_id AND `status` = 2");
$completed = mysql_fetch_assoc($completedQuery);
There has to be a better way to do that, right? I don't know how much I need to elaborate as you can see what I'm trying to do, but is there any way to do all of that in one query? I need to be able to output the active, failed, and completed assignments, preferably in one query.